根据类似的行值创建新列

时间:2014-11-03 13:20:44

标签: r

如何根据匹配的行值创建一组新的数据框列? 例如,对于此示例数据框:

x<-data.frame(cbind(numsp=rep(c(16,64,256),each=12),Colless=rep(c("loIc","midIc","hiIc"),each=4, times=3), lambdaE=rep(c(TRUE,FALSE),each=2,times=9),ntree=rep(c(1,2),length.out=36), metric1=seq(1:36), metric2=seq(1:36)))

enter image description here

对于某些参数,例如lambdaE,我想根据lambdaE是TRUE还是FALSE为metric1和metric 2创建新列。 数据框看起来像这样:

x2<-data.frame(cbind(numsp=rep(c(16,64,256),each=6),Colless=rep(c("hiIc","loIc","midIc"),each=2, times=3), ntree=rep(c(1,2),length.out=18), metric1.lambdE.FALSE=c(11,12,3,4,7,8,35,36,27,28,31,32,23,24,15,16,19,20), metric2.lambdE.FALSE=c(11,12,3,4,7,8,35,36,27,28,31,32,23,24,15,16,19,20),metric1.lambdE.TRUE=c(9,10,1,2,5,6,33,34,25,26,29,30,21,22,13,14,17,18), metric2.lambdE.TRUE=c(9,10,1,2,5,6,33,34,25,26,29,30,21,22,13,14,17,18)))

enter image description here

或者对于参数&#34; Colless&#34;,为每个级别的Colless建立一组新的metric1和metric2。

提前致谢!

2 个答案:

答案 0 :(得分:2)

好的,貌似图书库reshape2有一个快速解决方案:

reshape(x, direction="wide", idvar=c("numsp","Colless","ntree"), timevar="lambdaE")

答案 1 :(得分:0)

还可以使用reshape2的熔化和dcast:

library(reshape2)
mm =melt(x, id=c('numsp','Colless','lambdaE','ntree'))
dcast(mm, numsp+Colless+ntree~lambdaE+variable)
   numsp Colless ntree FALSE_metric1 FALSE_metric2 TRUE_metric1 TRUE_metric2
1     16    hiIc     1            11            11            9            9
2     16    hiIc     2            12            12           10           10
3     16    loIc     1             3             3            1            1
4     16    loIc     2             4             4            2            2
5     16   midIc     1             7             7            5            5
6     16   midIc     2             8             8            6            6
7    256    hiIc     1            35            35           33           33
8    256    hiIc     2            36            36           34           34
9    256    loIc     1            27            27           25           25
10   256    loIc     2            28            28           26           26
11   256   midIc     1            31            31           29           29
12   256   midIc     2            32            32           30           30
13    64    hiIc     1            23            23           21           21
14    64    hiIc     2            24            24           22           22
15    64    loIc     1            15            15           13           13
16    64    loIc     2            16            16           14           14
17    64   midIc     1            19            19           17           17
18    64   midIc     2            20            20           18           18