I've worked with R for quite some time now, but have made little use of the reshape or reshape2 packages. I'm currently trying to reshape a data set from wide to long format where the indicator variables are part of the variable names. This is the current structure of my data frame:
mydf <- data.frame(district = c(1:2),
v.mandate = c(1, 3),
s.mandate = c(2, 4),
v.perc = c(.4, .3),
s.perc = c(.5, .6))
> mydf
district v.mandate s.mandate v.perc s.perc
1 1 1 2 0.4 0.5
2 2 3 4 0.3 0.6
I want to reshape this to long format and extract the "v." and "s." as id variables (in the real data set the list is longer). See example below.
mydf2 <- data.frame(district = c(1, 1, 2, 2),
party = c("v", "s", "v", "s"),
mandate = c(1, 2, 3, 4),
perc = c(.4, .5, .3, .6))
> mydf2
district party mandate perc
1 1 v 1 0.4
2 1 s 2 0.5
3 2 v 3 0.3
4 2 s 4 0.6
I have tried using both the reshape and melt functions, but I can't seem to extract the indicator variables from the variable names. Instead, the data set is reshaped into long format, but with the full variable names as id variables. See example below.
> melt(mydf, id.vars=1)
district variable value
1 1 v.mandate 1.0
2 2 v.mandate 3.0
3 1 s.mandate 2.0
4 2 s.mandate 4.0
5 1 v.perc 0.4
6 2 v.perc 0.3
7 1 s.perc 0.5
8 2 s.perc 0.6
It might be a trivial problem, but I haven't been able to find a solution on-line.
Greatly appreciate any help!