I want to change a table from long to wide. It has multiple values and a categorical variables.
table looks like:
df <- data.frame(name = c("john", "mary", "john", "mary"),
variable = c("math", "math", "science", "science"),
grade = c("sixth", "sixth", "sixth", "sixth"),
val1 = c(78, 88, 97, 100), val2 = c(92, 83, 69, 94))
What I want is this:
want <- data.frame(name = c("john", "mary"), grade = c("sixth", "sixth"),
math.val1 = c(78, 88), math.val2 = c(92, 83), science.val1 = c(97, 100),
science.val2 = c(69, 94))
Without the grade column, I am able to achieve this easily:
reshape(df, idvar='name', timevar='variable', direction='wide')
With the "grade" column, I get :
name grade.math val1.math val2.math grade.science val1.science val2.science
1 john sixth 78 92 sixth 97 69
2 mary sixth 88 83 sixth 100 94
How can I correct this?
Thanks.