我有一个数据框:
something<-data.frame( Drug=rep(c(1,2), each=6), Plant=c(rep("A",2),rep("B",2),rep("C",2)), dmso=c(0.407,0.374,0.452,0.429,0.439,0.436,0.441,0.453,0.439,0.436,0.452,0.429), One=c(0.241,0.237,0.455,0.436,0.453,0.433,0.47,0.461,0.453,0.433,0.455,0.436), Two=c(0.065,0.07,0.513,0.542,0.064,0.074,0.5,0.494,0.064,0.074,0.513,0.542), Three=c(0.063,0.068,0.678,0.631,0.068,0.073,0.449,0.521,0.068,0.073,0.678,0.631) )
我想创建一个新的数据框,其中的行将代表药物治疗植物的手段。 例如:
如果这是一个重复的帖子,我很抱歉,但我无法在其他任何地方找到解决方案。谢谢:))
答案 0 :(得分:1)
可以使用aggregate()
:
aggregate(.~Drug+Plant,something,mean);
## Drug Plant dmso One Two Three
## 1 1 A 0.3905 0.2390 0.0675 0.0655
## 2 2 A 0.4470 0.4655 0.4970 0.4850
## 3 1 B 0.4405 0.4455 0.5275 0.6545
## 4 2 B 0.4375 0.4430 0.0690 0.0705
## 5 1 C 0.4375 0.4430 0.0690 0.0705
## 6 2 C 0.4405 0.4455 0.5275 0.6545
##类'公式'的S3方法
聚合(公式,数据, FUN ,..., 子集, na.action = na.omit)...
式
a formula,例如y~x或cbind(y1,y2)~x1 + x2,其中y变量是根据分组x变量(通常是因子)分成组的数值数据。
可以在formula的文档页面上找到公式中.
字符特殊用途的文档:
有两种特殊的解释。在公式中。通常的一个是在模型拟合函数的数据参数的上下文中,并且意味着“公式中没有其他列的所有列”:参见terms.formula。仅在update.formula的上下文中,它表示“此前公式中的内容”。
data.table
解决方案:
library(data.table);
dt <- as.data.table(something);
dt[,lapply(.SD,mean),.(Drug,Plant)];
## Drug Plant dmso One Two Three
## 1: 1 A 0.3905 0.2390 0.0675 0.0655
## 2: 1 B 0.4405 0.4455 0.5275 0.6545
## 3: 1 C 0.4375 0.4430 0.0690 0.0705
## 4: 2 A 0.4470 0.4655 0.4970 0.4850
## 5: 2 B 0.4375 0.4430 0.0690 0.0705
## 6: 2 C 0.4405 0.4455 0.5275 0.6545