data.frame 中每组的平均值 [英] Mean per group in a data.frame

查看:46
本文介绍了data.frame 中每组的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 data.frame,我需要计算每个组的平均值(即每个 Month,如下).

I have a data.frame and I need to calculate the mean per group (i.e. per Month, below).

Name     Month  Rate1     Rate2
Aira       1      12        23
Aira       2      18        73
Aira       3      19        45
Ben        1      53        19
Ben        2      22        87
Ben        3      19        45
Cat        1      22        87
Cat        2      67        43
Cat        3      45        32

我想要的输出如下所示,其中 Rate1Rate2 的值是组均值.请忽略该值,我已经为示例补上了.

My desired output is like below, where the values for Rate1 and Rate2 are the group means. Please disregard the value, I have made it up for the example.

Name       Rate1       Rate2
Aira        23.21       12.2
Ben         45.23       43.9
Cat         33.22       32.2

推荐答案

这种类型的操作正是 aggregate 的设计目的:

This type of operation is exactly what aggregate was designed for:

d <- read.table(text=
'Name     Month  Rate1     Rate2
Aira       1      12        23
Aira       2      18        73
Aira       3      19        45
Ben        1      53        19
Ben        2      22        87
Ben        3      19        45
Cat        1      22        87
Cat        2      67        43
Cat        3      45        32', header=TRUE)

aggregate(d[, 3:4], list(d$Name), mean)

  Group.1    Rate1    Rate2
1    Aira 16.33333 47.00000
2     Ben 31.33333 50.33333
3     Cat 44.66667 54.00000

这里我们聚合 data.frame d 的第 3 列和第 4 列,按 d$Name 分组,并应用 mean 函数.

Here we aggregate columns 3 and 4 of data.frame d, grouping by d$Name, and applying the mean function.

或者,使用公式界面:

aggregate(. ~ Name, d[-2], mean)

这篇关于data.frame 中每组的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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