R问题:如何堆叠两列或更多列数字并保留一个因子
我data.frame喜欢这样的:
patient analyte1value analyte2value analyte3value
pt1 1 3 5
pt2 2 6 7
pt3 9 10 2
...
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用stack(select=c(columnnames)),但我失去了耐心因素.
我想出去:
pt1 1 analyte1
pt1 3 analyte2
pt1 5 analyte3
pt2 2 analyte1
pt2 6 analyte2
...
Run Code Online (Sandbox Code Playgroud)
(我有一种潜在的怀疑,我需要plyr或类似的......)
谢谢.
一种选择是Hadley的其他套餐之一reshape2:
> require(reshape2)
> dat
patient analyte1 analyte2 analyte3
1 pt1 1 3 5
2 pt2 2 6 7
3 pt3 9 10 2
> melt(dat, id = "patient")
patient variable value
1 pt1 analyte1 1
2 pt2 analyte1 2
3 pt3 analyte1 9
4 pt1 analyte2 3
5 pt2 analyte2 6
6 pt3 analyte2 10
7 pt1 analyte3 5
8 pt2 analyte3 7
9 pt3 analyte3 2
> str(melt(dat, id = "patient"))
'data.frame': 9 obs. of 3 variables:
$ patient : Factor w/ 3 levels "pt1","pt2","pt3": 1 2 3 1 2 3 1 2 3
$ variable: Factor w/ 3 levels "analyte1","analyte2",..: 1 1 1 2 2 2 3 3 3
$ value : int 1 2 9 3 6 10 5 7 2
Run Code Online (Sandbox Code Playgroud)
人们可以使用reshape()基础R 以更加冗长的方式做到这一点:
reshape(dat, direction = "long", sep = "", varying = 2:4,
times = names(dat)[2:4], idvar = "patient",
timevar = "variable", v.names = "value")
Run Code Online (Sandbox Code Playgroud)
主要区别在于variable不是基数因素reshape().我认为用户不友好是写作的动机reshape2......