calculate the mean by group in r

To calculate the mean by group in R, we can use the dplyr package from the tidyverse. Specifically, we can use the group_by and summarize functions to group our data by a certain variable and then calculate the mean for each group.

Here is an example using the built-in mtcars dataset:

main.r
library(dplyr)

# calculate the mean mpg for each number of cylinders
mtcars %>%
  group_by(cyl) %>%
  summarize(avg_mpg = mean(mpg))
134 chars
7 lines

This will output a table with the average mpg for each number of cylinders in the mtcars dataset:

main.r
# A tibble: 3 x 2
    cyl avg_mpg
  <dbl>   <dbl>
1     4    26.7
2     6    19.7
3     8    15.1
98 chars
7 lines

gistlibby LogSnag