如何将聚合与列名列表一起使用 [英] How to use aggregate with a list of column names

查看:85
本文介绍了如何将聚合与列名列表一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过传递要汇总的条件和值列表来抽象函数中的聚合

How do you abstract aggregate in a function by passing a list of conditions and values to summarize?

# This works fine:
x <- data.frame(cond1 = sample(letters[1:3], 500, replace=TRUE), 
                cond2 = sample(LETTERS[1:7], 500, replace = TRUE), 
                cond3 = sample(LETTERS[1:4], 500, replace = TRUE), 
                value1 = rnorm(500), 
                value2 = rnorm(500))

aggregate(cbind(value1,value2) ~ cond1 + cond2, data = x, FUN=sum)

需要创建列名列表:(显示3个选项),然后调用函数:

Need to create a list of column names: (3 options shown) then call the function:

c1 <- c("cond1","cond2","cond3"); v1 <- c("value1","value2")
c1 <- c("cond2","cond3");         v1 <- c("value2")
c1 <- c("cond3");                 v1 <- c("value1")

aggregate(cbind(v1) ~ c1, data = x, FUN=sum)

我查看了许多替代方法,但尚未发现抽象的关键。

I have reviewed many alternatives, but have not yet discovered the key to this abstraction.

推荐答案

您可以使用替代接口聚合,该接口不使用公式:

You can use the alternative interface to aggregate, which does not use a formula:

c1 <- c("cond1","cond2","cond3")
v1 <- c("value1","value2")
aggregate(x[v1],by=x[c1],FUN=sum)

   cond1 cond2 cond3     value1      value2
1      a     A     A -3.3025839 -0.98304649
2      b     A     A  0.6326985 -3.08677485
3      c     A     A  3.6007853  2.23962265
4      a     B     A -0.5247620 -0.94644740
5      b     B     A  0.9242562  2.48268452
6      c     B     A  6.9215712  0.31512645

这篇关于如何将聚合与列名列表一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆