I want a function taking an unevaluated expression containing variable names into a new expression containing string for the variable names.
c(a,b)
should be converted to
c("a","b")
How can this be done?
Let me explain in more detail what I want to achieve.
my_tibble <-
tibble(a=rep(c("a","b"),each=4),
b=rep(rep(c("x","y"),each=2),2),
x=seq_along(b)
)
summary_groupwise <- function(data,group_var,var_to_summarise,result_var){
data |>
group_by({{group_var}}) |>
summarise({{result_var}} := sum({{var_to_summarise}}))
}
This function works
summary_groupwise(my_tibble,a,x,group_sum)
Now I want to group by multiple variables
summary_groupwise_multiple <- function(data,group_vars,var_to_summarise,result_var){
data |>
group_by(across(all_of({{group_vars}}))) |>
summarise({{result_var}} := sum({{var_to_summarise}}))
}
This works:
summary_groupwise_multiple(my_tibble,c("a","b"),x,group_sums)
To make summary_groupwise_multiple
work, the names of the grouping variables have to be given as strings.
For consistency of the syntax, I would like the following call to work
summary_groupwise_multiple(my_tibble,c(a,b),x,group_sums)
How can is fiddle with the parameter group_vars
so the call works without giving the names of the variables as strings.
CodePudding user response:
If the expressions are passed as a vector i.e. with c()
, an option is
f1 <- function(expr) {dput(sapply(as.list(substitute(expr))[-1], deparse))}
> f1(c(a, b))
c("a", "b")
CodePudding user response:
fun <- function(x)dput(as.character(substitute(x)[-1]))
fun(c(a, b, c))
c("a", "b", "c")