如何将不同的聚合函数应用于R中的不同列? [英] How can I apply different aggregate functions to different columns in R?

查看:98
本文介绍了如何将不同的聚合函数应用于R中的不同列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将不同的聚合函数应用于R中的不同列? aggregate()函数仅提供一个要传递的函数参数:

How can I apply different aggregate functions to different columns in R? The aggregate() function only offers one function argument to be passed:

V1  V2        V3
1   18.45022  62.24411694
2   90.34637  20.86505214
1   50.77358  27.30074987
2   52.95872  30.26189013
1   61.36935  26.90993530
2   49.31730  70.60387016
1   43.64142  87.64433517
2   36.19730  83.47232907
1   91.51753  0.03056485
... ...       ...

> aggregate(sample,by=sample["V1"],FUN=sum)
  V1 V1       V2       V3
1  1 10 578.5299 489.5307
2  2 20 575.2294 527.2222

如何将 different 函数应用于每列,即,将V2mean()函数聚合,将V2sum()函数聚合,而无需多次调用aggregate() ?

How can I apply a different function to each column, i.e. aggregate V2 with the mean() function and V2 with the sum() function, without calling aggregate() multiple times?

推荐答案

对于该任务,我将在plyr

> library(plyr)
> ddply(sample, .(V1), summarize, V2 = sum(V2), V3 = mean(V3))
  V1       V2       V3
1  1 578.5299 48.95307
2  2 575.2294 52.72222

这篇关于如何将不同的聚合函数应用于R中的不同列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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