I am trying to construct a formula using NSE so that I can easily pipe in columns. The following is my desired use case:
df %>% make_formula(col1, col2, col3)
[1] "col1 ~ col2 + col3"
I have made first this function:
varstring <- function(...) {
as.character(match.call()[-1])
}
This works great with either single objects or multiple objects:
varstring(col)
[1] "col"
varstring(col1, col2, col3)
[1] "col1" "col2" "col3"
I create my function to create the formula next:
formula <- function(df, col, ...) {
group <- varstring(col)
vars <- varstring(...)
paste(group,"~", paste(vars, collapse = " + "), sep = " ")
}
However, the function call formula(df, col, col1, col2, col3)
produces [1] "group ~ ..1 + ..2 + ..3"
.
I understand that the formula is literally evaluating varstring(group)
and varstring(...)
and not actually substituting in the user supplied objects for evaluation like I would like it too. But I can not figure out how to make this work as intended.