How can I calculate the conditional count and mean by grouped data without filter using dplyr? I neither want to shrink the dataset using filter nor want to left_join the data to get the original sized (lengthed) dataset. Is that possible?
Here is a case:
mtcars %>% filter(cyl>4, gear<5) %>% group_by(gear, carb, am) %>% mutate(avg_mpg = mean(mpg, na.rm = T), cnt = n())
How can I get the above results without using filter or left_join?
mtcars %>% group_by(gear, carb, am) %>% mutate(avg_mpg = mean(mpg[cyl>4 & gear< 5], na.rm = TRUE))
– akrunmtcars %>% group_by(gear, carb, am) %>% mutate(avg_mpg = mean(mpg[cyl>4 & gear< 5], na.rm = TRUE), cnt= n())
– akruncnt = sum(cyl>4 & gear <5))
– akrun