rlang - create string with curly curly to be evaluated later

Viewed 107

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:

  • Is it possible to create a string with the curly curly without evaluating it when the curly curly is first called?
  • How can I pass an empty string to rlang::parse_expr() ?

Thank you

1 Answers

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)
}
Related