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

查看:26
本文介绍了使用 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 库.那个包里还有一个summarise

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天全站免登陆