使用dplyr包按组计算平均值 [英] Calculate mean by group using dplyr package

查看:502
本文介绍了使用dplyr包按组计算平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用来自ggplot2的著名数据集钻石数据练习dplyr软件包。
我想计算按变量切工分组的钻石的平均价格。
我的代码如下。

I'm practicing dplyr package using famous dataset from ggplot2, 'diamonds' data. I am trying to calculate mean 'price' of diamonds grouped by variable 'cut'. My code is as following.

price.cut <- diamonds %>%
group_by(cut) %>%
summarize(Mean = mean(price, na.rm=TRUE))

我的期望是得到按切变量分组的平均价格。但是,我只能得到一个值,即总价格平均值。

My expectation is to get mean price grouped by 'cut' variable. However, I only get one value, the total mean of price.

>price.cut
   Mean
1 3932.8

我在做什么错了?

推荐答案

原因可能是我们不小心加载了 plyr 库。该程序包中还包含摘要

The reason could be that we accidentally loaded the plyr library. There is a summarise in that package as well

diamonds %>%
    group_by(cut) %>%
    dplyr::summarize(Mean = mean(price, na.rm=TRUE))
# A tibble: 5 x 2
#        cut     Mean
#      <ord>    <dbl>
#1      Fair 4358.758
#2      Good 3928.864
#3 Very Good 3981.760
#4   Premium 4584.258
#5     Ideal 3457.542






如果我们使用 plyr :: summarise

diamonds %>% 
   group_by(cut) %>%
   plyr::summarize(Mean = mean(price, na.rm=TRUE))
#    Mean
#1 3932.8

这篇关于使用dplyr包按组计算平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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