通过R中的条件计算平均值 [英] calculate a mean by criteria in R

查看:697
本文介绍了通过R中的条件计算平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过引入特定标准来计算R中的样本均值.例如,我有此表,并且我只想要stage = 1或2的那些人的均值:

I would like to calculate a sample mean in R by introducing a specific criteria. For example I have this table and I want the means of only those for whom stage = 1 or 2:

treatment session period stage wage_accepted type 
1            1      1     1            25  low 
1            1      1     3            19  low 
1            1      1     3            15  low 
1            1      1     2            32 high 
1            1      1     2            13  low 
1            1      1     2            14  low 
1            1      2     1            17  low 
1            1      2     4            16  low
1            1      2     5            21  low

在这种情况下所需的输出应该是:

The desired out in this case should be:

   stage  mean
      1  21.0 
      2  19.6667

谢谢.

推荐答案

使用dplyr

library(dplyr)

df %>% filter(stage==1 | stage ==2) %>% group_by(stage) %>%
  summarise(mean=mean(wage_accepted))

如果您不熟悉dplyr,请做一些解释:

If you are new to dplyr a bit of explanation:

先获取数据帧df,然后获取filter,其中stage等于1或2.然后为stage中的每个group计算wage_acceptedmean

Take the data frame df then filter where stage is equal to 1 or 2. Then for each group in stage calculate the mean of the wage_accepted

这篇关于通过R中的条件计算平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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