R 函数学习 - melt(),cast()

2020-05-18  本文已影响0人  Thinkando

reshape2包:

tidyr包:

data.table包:

melt(data, id.vars, measure.vars, variable.name = "variable", ..., na.rm = FALSE, value.name = "value")
其中id.vars是指定固定的列(原始的列仍然在列名上)
measure.vars是需要合并的列
variable.name是指合并后原来列名的新名字
value.name是相对应的值的新名字
> library(data.table)
> ID <- c(NA,1,2,2)
> Time <- c(1,2,NA,1)
> X1 <- c(5,3,NA,2)
> X2 <- c(NA,5,1,4)
> mydata <- data.table(ID,Time,X1,X2)
> mydata
   ID Time X1 X2
1: NA    1  5 NA
2:  1    2  3  5
3:  2   NA NA  1
4:  2    1  2  4
> md <- melt(mydata, id=c("ID","Time"))
> md
   ID Time variable value
1: NA    1       X1     5
2:  1    2       X1     3
3:  2   NA       X1    NA
4:  2    1       X1     2
5: NA    1       X2    NA
6:  1    2       X2     5
7:  2   NA       X2     1
8:  2    1       X2     4
image.png
上一篇下一篇

猜你喜欢

热点阅读