In base R
, we could construct the formula from unquoted arguments by first converting to string with deparse/substitute
and then use paste
to create the formula
foo <- function(data, col1, col2) {
col1 <- deparse(substitute(col1))
col2 <- deparse(substitute(col2))
boxplot(
formula = as.formula(paste0(col1, "~", col2)),
data = data)
}
-test it with inbuilt dataset
foo(mtcars, mpg, cyl)

Or if we prefer to use tidyverse
, use the curly-curly ({{..}}
) operator for simultaneously convert to quosures (enquo
) and evaluate (!!
)
library(dplyr)
library(ggplot2)
foo2 <- function(data, col1, col2) {
data %>%
select({{col1}}, {{col2}}) %>%
mutate( {{col2}} := factor({{col2}})) %>%
ggplot(aes(x = {{col2}}, y = {{col1}})) +
geom_boxplot()
}
foo2(mtcars, mpg, cyl)
