In the help files for dcast.data.table, there is a note stating that a new feature has been implemented: \"dcast.data.table allows value.var column to be of typ
Using sample data frame mydf from A5C1D2H2I1M1N2O1R2T1's answer.
tidyrReshape2 has been replaced with the tidyr package.
library(tidyr)
mydf %>%
gather(variable, value, -x1, -x2) %>%
unite(x2_variable, x2, variable) %>%
spread(x2_variable, value)
# x1 1_salt 1_sugar 2_salt 2_sugar 3_salt 3_sugar
# 1 1 3 1 4 2 6 2
# 2 2 10 5 3 3 9 6
# 3 3 10 4 7 6 7 7
reshape2@AlexR added to his question:
Sure, you can 'melt' the 2 value variables into a single column,
For those who come here looking for an answer based on reshape2, here is how to melt the data and then use dcast based on the "variable". .
dt2 <- melt(mydf, id = c("x1", "x2"))
The variable column will now contain 'var1','var2','var3'. You can achieve the desired effect with
dt3 <- dcast(dt2, x1 ~ x2 + variable, value.var="value")
dt3
# x1 1_salt 1_sugar 2_salt 2_sugar 3_salt 3_sugar
# 1 1 3 1 4 2 6 2
# 2 2 10 5 3 3 9 6
# 3 3 10 4 7 6 7 7
value.var is optional in this function call as dcast will automatically guess it.