根据两列查找唯一组合并计算平均值 [英] Find unique combinations based on two columns and calculate the mean
本文介绍了根据两列查找唯一组合并计算平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 R 中有一个问题,我似乎无法解决.
I have a problem in R, which I can't seem to solve.
我有以下数据框:
我想:
- 找到物种"和影响"列的独特组合
- 报告属于这个独特组合的浓度
- 如果这种独特的组合出现多次,计算平均浓度
并希望获得以下数据框:
And would like to get the following dataframe:
我尝试了下一个脚本来获得独特的组合:
I have tried next script to get the unique combinations:
UniqueCombinations <- Data[!duplicated(Data[,1:2]),]
UniqueCombinations <- Data[!duplicated(Data[,1:2]),]
但不知道如何从那里开始.
but don't know how to proceed from there.
预先感谢您的回答!
蒂娜
推荐答案
请尝试以下操作(感谢 Brandon Bertelsen 的精彩评论):
Try the following (Thanks Brandon Bertelsen for nice comment):
创建数据:
foo = data.frame(Species=c(rep("A",4),"B",rep("C",3),"D","D"),
Effect=c(rep("Reproduction",3), rep("Growth",2),
"Reproduction", rep("Mortality",2), rep("Growth",2)),
Concentration=c(1.2,1.4,1.3,1.5,1.6,1.2,1.1,1,1.3,1.4))
使用很棒的包 plyr
来一点魔法:)
Using great package plyr
for a bit of magic :)
library(plyr)
ddply(foo, .(Species,Effect), function(x) mean(x[,"Concentration"]))
这是一个更复杂但更干净的版本(再次感谢 Brandon Bertelsen):
And this is a bit more complicated, but cleaner version (Thanks again to Brandon Bertelsen):
ddply(foo, .(Species,Effect), summarize, mean=mean(Concentration))
这篇关于根据两列查找唯一组合并计算平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文