28

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

What am I doing wrong?

pogibas
  • 27,303
  • 19
  • 84
  • 117
Daniel Cho
  • 797
  • 1
  • 7
  • 13

1 Answers1

62

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

If we use the plyr::summarise

diamonds %>% 
   group_by(cut) %>%
   plyr::summarize(Mean = mean(price, na.rm=TRUE))
#    Mean
#1 3932.8
akrun
  • 874,273
  • 37
  • 540
  • 662