Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate mean by group using dplyr package [duplicate]

Tags:

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?

like image 475
Daniel Cho Avatar asked Oct 10 '17 07:10

Daniel Cho


1 Answers

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 
like image 173
akrun Avatar answered Sep 30 '22 01:09

akrun