I found this very helpful article on how to write a function accepting variable arguments using quosure and tidy dots. Here's some of the code:
my.summary <- function(df.name=df_tp1, group_var, ...) {
group_var <- enquo(group_var)
smry_vars <- enquos(..., .named = TRUE)
the.mean <- purrr::map(smry_vars, function(var) {
expr(mean(!!var, na.rm = TRUE))
})
names(the.mean) <- paste0("mean-", names(the.mean))
df.name %>%
group_by(!!group_var) %>%
summarise(!!!the.mean)
}
The problem is I have to call the function with a long string of variables, like this:
cm_all1 <- my.summary(df_tp1_cm, group_var=net_role, so_part_value, cult_ci, cult_sn, cult_ebc, sl_t_lrn, sl_xt_lrn, nl_netops_km, so_rt, nl_netops_trust)
I would be very happy to be able to just call it with something like
so_part_value:nl_netops_trust
instead, but this gives errors like this:
Error in so_part_value:nl_netops_trust : NA/NaN argument
I also tried putting the variable names in a character vector and then using enquo() and !! but that didn't work.
I'd appreciate any ideas.
Here is my rewrite of the function using Yifu's ideas. This works for my fake data set but not the real data.
my.summary <- function(df.name=df_tp1, group_var, ...) {
## group_var <- enquo(group_var)
smry_vars <- df.name %>% select(...) %>% colnames()
df.name %>%
## group_by(!!group_var) %>%
group_by({{group_var}}) %>%
summarise_at(smry_vars,
list(mean=function(x) mean(x, na.rm=TRUE),
sd=function(x) sd(x, na.rm=TRUE),
min=function(x) min(x, na.rm=TRUE),
max=function(x) max(x, na.rm=TRUE),
q1=function(x) quantile(x, .25, na.rm=TRUE),
q2=function(x) quantile(x, .50, na.rm=TRUE),
q3=function(x) quantile(x, .75, na.rm=TRUE),
n=function(x) n()
))
}