data1=data.frame("grade"=c(rep(1:3,6)),
"class" = c(rep(c(rep('a',3),rep('b',3)),3)),
"score"=c(rep(c('p','p','p','s','s','s','q','q','q'),2)),
"p"=c(-9:8),
"s"=c(1:18),
"q"=c(21:38))
data2=data.frame("grade"=c(rep(1:3,6)),
"class" = c(rep(rep('a',3),rep('b',3),3)),
"pp"=c(-9,-8,-7,0,1,2),
"ps"=c(1,2,3,10,11,12),
"pq"=c(21,22,23,30,31,32),
"sp"=c(-6,-5,-4,3,4,5),
"ss"=c(4,5,6,13,14,15),
"sq"=c(24,25,26,33,34,35),
"qp"=c(-3,-2,-1,6,7,8),
"qs"=c(7,8,9,16,17,18),
"qq"=c(27,28,29,36,37,38))
What I have is data1 and I want to make data2. My english is not so good and so I made these two example data frames to show what I wish for. Basically to combine 'score' from 'data1' with column names 'p' and 'q' and 'q' from data1 to create 'data2'.
I have big student district data so wish for a fast data.table solution if it is possible. Also am interested to see dplyr or other simple solution!
Then I wonder how to ggplot all columns of 'data2' [pp-qq] by grade AND 'class'
dcast(setDT(data1), grade + class + rowid(score) ~ score, value.var = c('p', 's', 'q'), sep="")[, score := NULL][]
Hopeful output in two steps, ultimate wish is one on bottom, one on top is intermediate-
_____________________________________________________________________________ A member gave me a very great answer on recasting the dataframe:
data1=data.frame("grade"=c(rep(1:3,6)),
"class" = c(rep(c(rep('a',3),rep('b',3)),3)),
"score"=c(rep(c('p','p','p','s','s','s','q','q','q'),2)),
"p"=c(-9:8),
"s"=c(1:18),
"q"=c(21:38))
d2=dcast(melt(setDT(data1), id.var = 1:3)[, c('score', 'variable') :=
lapply(.SD, function(x) setNames(c(3, 5, 9), c('p', 's', 'q'))[x]),
.SDcols = c('score', 'variable')],grade + class ~
paste0('x', score, variable), value.var = 'value')
It works perfect. In my application however I have many more variables. When I go to even add just 1 I break it:
data1=data.frame("col1"=c(1),
"grade"=c(rep(1:3,6)),
"class" = c(rep(c(rep('a',3),rep('b',3)),3)),
"score"=c(rep(c('p','p','p','s','s','s','q','q','q'),2)),
"p"=c(-9:8),
"s"=c(1:18),
"q"=c(21:38))
d2=dcast(melt(setDT(data1), id.var = 1:3)[, c('score', 'variable') :=
lapply(.SD, function(x) setNames(c(3, 5, 9), c('p', 's', 'q'))[x]),
.SDcols = c('score', 'variable')], col1 + grade + class ~
paste0('x', score, variable), value.var = 'value')
Error in [.data.table(melt(setDT(data1), id.var = 1:3), , :=(c("score", : Some items of .SDcols are not column names: [score] In addition: Warning message: In melt.data.table(setDT(data1), id.var = 1:3) : 'measure.vars' [score, p, s, q] are not all of the same type. By order of hierarchy, the molten data value column will be of type 'character'. All measure variables not of type 'character' will be coerced too. Check DETAILS in ?melt.data.table for more on coercion.
Maybe there is a way to do it less likely to break? Your aid is much appreciated!

