Fun problem!
I made some slight changes. For example, I added data %>% to code1 and code2 because I can't remember how to concatenate that programmatically. I prefer rlang to base R's metaprogramming. You can read the metaprogramming section of Advanced R for a deep dive or this PDF cheat sheet for a quick intro.
I used dplyr::enexpr, replacing eval(substitute(...)). You also mistyped some of the column names, e.g. states which should have been state.
Lastly, I used rlang::eval_tidy to run the code.
I haven't checked that the output is correct, however. I'll leave that to you, and please let me know!
apply_conditional_summary <- function(data, code1, code2) {
if ("category" %in% colnames(data)) {
result <- enexpr(code2)
} else {
result <- enexpr(code1)
}
return(rlang::eval_tidy(result))
}
apply_conditional_summary(
df2,
data %>% group_by(date, state) %>% summarise(units = mean(units), total_amt = sum(amount), .groups = "drop"),
data %>% group_by(date, state, category) %>%
summarise(units = mean(units), total_amt = sum(amount), .groups = "drop") %>%
group_by(date, state) %>%
mutate(share = total_amt / sum(total_amt)) %>%
ungroup()
)