I am trying to create a string that includes the "curly curly" brackets and the object based by the user. I will then parse and evaluate this expression inside of ggplot command.
test_func <- function(df, x_var, y_var, color_by){
color_aes <- ifelse(!missing(color_by),
glue::glue("aes(color = {{{color_by}}})"), "") %>%
rlang::expr()
df %>%
ggplot(aes(x = {{x_var}}, y = {{y_var}})) +
geom_point(rlang::eval_tidy(rlang::parse_expr(color_aes)))
}
test_func(mtcars, cyl, disp)
test_func(mtcars, cyl, disp, carb)
Two questions:
rlang::parse_expr()
?Thank you
I woudn't recommend using strings in this case. You should be able to work with aes()
objects more easily. For example
test_func <- function(df, x_var, y_var, color_by){
color_aes <- if(!missing(color_by))
aes(color = {{color_by}}) else aes()
df %>%
ggplot(aes(x = {{x_var}}, y = {{y_var}})) +
geom_point(color_aes)
}