我正在使用dcast.data.table将一个长数据表转换为宽数据表。
library(data.table)
library(reshape2)
set.seed(1234)
dt.base <- data.table(A = rep(c(1:3),2), B = rep(c(1:2),3), C=c(1:4,1,2),thevalue=rnorm(6))
#from long to wide using dcast.data.table()
dt.cast <- dcast.data.table(dt.base, A ~ B + C, value.var = "thevalue", fun = sum)
#now some stuff happens e.g., please do not bother what happens between dcast and melt
setkey(dt.cast, A)
dt.cast[2, c(2,3,4):=1,with = FALSE]
现在我想将data.table再次还原为原始列布局,但是我卡住了,我该如何从转换后的data.table中分离出拼接的列名呢?这就是我的问题。
dt.melt <- melt(dt.cast,id.vars = c("A"), value.name = "thevalue")
我需要两列而不是一列
使用以下代码可以得到我想要的结果
#update
dt.base[A==2 & B == 1 & C == 1, thevalue :=1]
dt.base[A==2 & B == 2 & C == 2, thevalue :=1]
#insert (2,1,3 was not there in the base data.table)
dt.newrow <- data.table(A=2, B=1, C=3, thevalue = 1)
dt.base <-rbindlist(list(dt.base, dt.newrow))
dt.base
一如既往,感谢您的帮助。
(注:本段内容无需翻译)
dt.melt
的variable
列即可。 - Ricardo Saporta