I want to summarize a dataframe by groups. The columns to group are defined dynamically in different compilations. An example is here.
gender = c(rep(1, 50), rep(2, 50))
weight = round(rnorm(100, 60, 5), 0)
age = floor(runif(100, min=18, max=30))
my_df <- data.frame(gender, age, weight)
result <- function(
df = my_df,
group_by_gender = TRUE,
group_by_weight = TRUE,
group_by_age = TRUE
){
the_result <- df %>%
group_by(
gender, #if(group_by_gender, gender, NULL),
weight, #if(group_by_weight, weight, NULL),
age #if(group_by_age, age, NULL)
) %>%
summarize(
count = n()
)
return(the_result)
}
Depending on the group_by_* i want to switch on or off none, one or more columns to group by. I do not see, how to construct the string inside group_by(string)