rlang - 创建带有 curly curly 的字符串以供稍后评估

rlang - create string with curly curly to be evaluated later

我正在尝试创建一个字符串,其中包含“大括号”和用户基于的对象。然后我将在 ggplot 命令中解析和评估这个表达式。

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)

两个问题:

谢谢

我不建议在这种情况下使用字符串。您应该能够更轻松地使用 aes() 对象。例如

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