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.