filtering within the summarise function of dplyr

We can try

 df %>%
     group_by(id, tp) %>%
     summarise(all_mean = mean(values), 
                A_mean = mean(values[value_type=="A"]),
                value_count=sum(value_type == 'A'))

You can do this with two summary steps:

df %>%
  group_by(id, tp, value_type) %>%
  summarise(A_mean = mean(values)) %>%
  summarise(all_mean = mean(A_mean),
            A_mean = sum(A_mean * (value_type == "A")),
            value_count = sum(value_type == "A"))

The first summary calculates the means per value_type and the second "sums" only the mean of value_type == "A"

Tags:

R

Dplyr