R中的多重聚合 [英] Multiple Aggregation in R

查看:99
本文介绍了R中的多重聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个参数(3列)

x <- c(1, 1, 2, 2, 2, 2, 1, 1, 2) 
y <- c(1, 1, 1, 2, 2, 2, 3, 3, 3) 

 z <- c(10, NA, 16, 25, 41, NA, 17, 53, 26)

每个<$ c我都需要$ c> y 计算列 z 的平均值,其中 x == 1

I need for each y calculate the mean of column z, where x==1

如何在R中使用 aggregate 函数做到这一点?

How can I do it using the aggregate function in R?

data <- data.frame(x=c(1, 1, 2, 2, 2, 2, 1, 1, 2), 
                   y=c(1, 1, 1, 2, 2, 2, 3, 3, 3), 
                   z=c(10, NA, 16, 25, 41, NA, 17, 53, 26))

data
  x y  z
1 1 1 10
2 1 1 NA
3 2 1 16
4 2 2 25
5 2 2 41
6 2 2 NA
7 1 3 17
8 1 3 53
9 2 3 26


推荐答案

这是解决问题的一种方法,使用 tapply

Here's one way of going about it, using tapply:

with(data, tapply(z, list(x==1, y), mean, na.rm=TRUE)['TRUE', ])

#  1  2  3 
# 10 NA 35

通常,将任意函数应用于 x == 1 ,并为具有 x == 1 NA c $ c>,我们可以使用聚合合并

More generally, to apply an arbitrary function to groups where x==1, and return NA for groups that don't have x==1, we can use aggregate and merge:

merge(aggregate(z~y, data[data$x==1,], function(x) {
 c(mean=mean(x, na.rm=TRUE), quantile(x, na.rm=TRUE))
}), list(y=unique(data$y)), all=TRUE)

#   y z.mean z.0% z.25% z.50% z.75% z.100%
# 1 1     10   10    10    10    10     10
# 2 2     NA   NA    NA    NA    NA     NA
# 3 3     35   17    26    35    44     53

这篇关于R中的多重聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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