dplyr calculating new column based on filtering, group, and summarise

Perhaps something like the following:

foo %>%
  # new column with only the values you want to average over, and NA elsewhere
  mutate(y_when_x_under_5 = ifelse(x <= 5, y, NA)) %>%
  # new column with mean for each group
  group_by(id) %>%
  mutate(y_mean = mean(y_when_x_under_5, na.rm = TRUE)) %>%
  # required calculation
  mutate(yAnom = y - y_mean)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top