I want to define a custom function which groups and summarises some data using dplyr, and conditional on a Boolean flag can group by an additional level. I can achieve this using a full if... else control block as in this trivial example:
library(tidyverse)
data(Titanic)
Titanic <- as_tibble(Titanic)
foo <- function(by_age = FALSE) {
if (by_age) {
bar <- Titanic %>%
group_by(Survived, Age)
} else {
bar <- Titanic %>%
group_by(Survived)
}
bar %>%
summarise(n = sum(n))
}
foo()
foo(by_age = TRUE)
But this seems a very clumsy way round. Is there a way I can achieve this with a single block of dplyr code, conditionally calling Age as a second grouping variable? I've tried with ifelse(by_age, Age, NA) in my group_by statement, and some of the techniques listed in this SO post but to no avail.