Calculate difference from the group mean using dplyr

Viewed 160

I want to calculate the difference each row has from its group's mean. Is there a way to do this without creating an intermediate table and joining it?

group_summary <- mtcars %>%
  group_by(cyl) %>%
  summarize(mean_mpg = mean(mpg))

left_join(mtcars, group_summary) %>%
  mutate(mpg_diff_from_group = mpg - mean_mpg)
3 Answers

Yes, the following works without intermediate table:

mtcars %>%
    group_by(cyl) %>%
    mutate(grouped_diff = mpg - mean(mpg)) %>%
    ungroup()

similar to the previous codes, instead of using mutate you can also summarize the data and then ungroup again

mtcars %>%
  group_by(cyl) %>%
  summarise(grouped_diff = mpg - mean(mpg)) %>%
  ungroup
mtcars  %>% group_by(cyl)   %>% mutate(mean_mpg = mean(mpg), mpg_diff_from_grp= mpg - mean_mpg)  %>% ungroup() 
Related