DEV Community

Joe Chelladurai
Joe Chelladurai

Posted on

R: Calculating averages

To calculate the average of a value we can use summarise from the dplyr package.

library(dplyr)
Enter fullscreen mode Exit fullscreen mode
mtcars %>%
  summarise(average_mileage = mean(mpg))
Enter fullscreen mode Exit fullscreen mode

mpg stands for miles per gallon. This gives us the average mileage of all the cars.

If we want to get averages for each cylinder type, then we can use the group_by function to separate the averages for each group.

mtcars %>%
  group_by(cyl) %>%
  summarise(average_mileage = mean(mpg))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)