简体   繁体   English

R:如何在“ by”是变量的函数中使用聚合?

[英]R: How do I use aggregate in a function where the 'by' is a variable?

I'm trying to write a function that creates new data frames with summarised columns. 我正在尝试编写一个函数,该函数创建带有汇总列的新数据框。 I can use aggregate individually: 我可以单独使用聚合:

df = aggregate(. ~ Family, data=df, FUN=sum)

But I want to replace the 'Family' with an object from a list: 但我想用列表中的对象替换“家庭”:

levels = c('Family','Order','Class','Phylum','Superkingdom')
for (i in 1:5){
    OTU = levels[i]
    df = lineage[,c(OTU,'Abundance')]
    df = aggregate(. ~ OTU, data=df, FUN=sum)
}

In the code above, 'lineage' in a data frame with the taxonomic levels for a selection of organisms, plus an abundance value. 在上面的代码中,在数据框中包含用于选择生物的分类级别的“谱系”,再加上丰度值。 What I'd like to do is create a new, summarised, data frame for each taxonomic level, with the abundance values being summarised. 我想做的是为每个分类级别创建一个新的,汇总的数据框,并汇总丰度值。

I've found many posts about aggregate on here, but still can't get it to work. 我在这里找到了许多有关聚合的帖子,但仍然无法正常工作。

Thanks in advance for any help! 在此先感谢您的帮助!

I include two variables to summarise in case you're interested in extending it beyond simply Abundance . 如果您有兴趣将其扩展到不仅仅是Abundance我将提供两个变量进行总结。 Something like this could work: 这样的事情可能会起作用:

set.seed(42)

taxa <- c('Family','Order','Class','Phylum','Superkingdom')
df <- data.frame(ID = 1:15, Abundance = runif(15), HomeRange = abs(rnorm(15)), taxa = rep(taxa, times = 3))

(output2 <- aggregate(cbind(HomeRange, Abundance) ~ taxa, data = df, FUN = sum))

With a result like this: 结果如下:

#           taxa HomeRange Abundance
# 1        Class  1.413938  1.355478
# 2       Family  2.556280  1.891644
# 3        Order  3.317171  2.392776
# 4       Phylum  2.129622  1.742869
# 5 Superkingdom  4.031149  1.809103

Similarly, for one variable: 同样,对于一个变量:

(output1 <- aggregate(Abundance ~ taxa, data = df, FUN = sum))

#           taxa Abundance
# 1        Class  1.355478
# 2       Family  1.891644
# 3        Order  2.392776
# 4       Phylum  1.742869
# 5 Superkingdom  1.809103

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM