I have a data set which I want to group and then get the maximum value, second largest value and total for each group output. On the example data set mtcars it looks like this:
df <- mtcars %>% group_by(cyl) %>%
dplyr::summarise(
MaxVal = max(hp, na.rm = T),
MAXsecVal = max(hp[hp != max(hp)], na.rm = F),
Sum = sum(hp)
) %>% arrange(cyl)
cyl MaxVal MAXsecVal Sum
<dbl> <dbl> <dbl> <dbl>
1 4 113 109 909
2 6 175 123 856
3 8 335 264 2929
and works. But now I would like to access the (max, sum) variables dynamically. The best way would be a character vector like this:
var <- c("hp", "drat", "wt")
which can be run over the existing programming by a loop or something similar. Does anyone have an idea?