2012-12-18 88 views
1

我有这个数据帧因子列和列因素

DFtest <- data.frame(Zone=rep(c("R1","R2","R3"),each=2), 
        Type=rep(c("C1","C2"),3), 
        N1=sample(1:6), 
        N2=sample(seq(0,1,length.out=6)), 
        N3=sample(letters[1:6])) 
DFtest 

    Zone Type N1 N2 N3 
1 R1 C1 2 0.4 c 
2 R1 C2 5 1.0 a 
3 R2 C1 4 0.6 e 
4 R2 C2 3 0.2 d 
5 R3 C1 1 0.0 b 
6 R3 C2 6 0.8 f 

我想因子类型转换为列和列N1到N3的因素。期望的最终结果应该是这样的:通过组合plyr,重塑,dcast,融化等,但我能找到正确的方式

Zone Ns Type.C1 Type.C2 
1 R1 N1  2  5 
2 R1 N2  0.4  1.0 
3 R1 N3  c  a 
4 R2 N1  4  3 
5 R2 N2  0.6  0.2 
6 R2 N3  e  d 
7 R3 N1  1  6 
8 R3 N2  0.0  0.8 
9 R3 N3  b  f 

我一直在试图完成的。非常感谢您

+2

每当你使用像'sample'这样的随机数生成的东西时,请考虑在你的示例数据中使用'set.seed()'。 – A5C1D2H2I1M1N2O1R2T1

回答

8

这里的 “reshape2” 的方法:

library(reshape2) 
DFtestL <- melt(DFtest, id.vars=1:2) 
dcast(DFtestL, Zone + variable ~ Type) 
# Zone variable C1 C2 
# 1 R1  N1 2 3 
# 2 R1  N2 0.2 0.4 
# 3 R1  N3 c d 
# 4 R2  N1 1 6 
# 5 R2  N2 0 0.8 
# 6 R2  N3 a b 
# 7 R3  N1 5 4 
# 8 R3  N2 0.6 1 
# 9 R3  N3 f e 

下面是使用reshape()aggregate()一个基础R的方法。行顺序可稍后使用order()进行修复。

DFtestL2 <- reshape(DFtest, direction = "long", 
        idvar=c("Zone", "Type"), 
        varying=3:ncol(DFtest), sep="") 
aggregate(N ~ Zone + time, DFtestL2, I) 
# Zone time N.1 N.2 
# 1 R1 1 2 3 
# 2 R2 1 1 6 
# 3 R3 1 5 4 
# 4 R1 2 0.2 0.4 
# 5 R2 2 0 0.8 
# 6 R3 2 0.6 1 
# 7 R1 3 c d 
# 8 R2 3 a b 
# 9 R3 3 f e 
+0

+1比我快10秒。 – Roland