使用dplyr包按组计算平均值

Dan*_*Cho 10 r dplyr

我正在使用来自ggplot2,'diamond'数据的着名数据集来练习dplyr包.我试图计算按变量'cut'分组的钻石的平均'价格'.我的代码如下.

price.cut <- diamonds %>%
group_by(cut) %>%
summarize(Mean = mean(price, na.rm=TRUE))
Run Code Online (Sandbox Code Playgroud)

我的期望是通过'cut'变量得到平均价格.但是,我只得到一个价值,即价格的总平均值.

>price.cut
   Mean
1 3932.8
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

akr*_*run 29

原因可能是我们不小心加载了plyr库.summarise该包中也有一个

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
Run Code Online (Sandbox Code Playgroud)

如果我们使用 plyr::summarise

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