使用 I 字符串来引用 dplyr 中的变量?

Use I string to refer to a variable inside dplyr?

假设我有以下数据:

test_df <- data.frame(a=rnorm(100), b=rnorm(100))

以下作品:

test_df %>% 
  summarise(y = mean(a))

现在假设我想传递一个字符串

而不是a
string_outcome <- "a" # I want to use this

test_df %>% 
  summarise(y = mean(string_outcome))

那不行。我尝试使用 !!string_outcome 但这也不起作用。我该如何解决这个问题?

因为它是一个字符串,将它转换为符号 (sym from rlang) 并计算 (!!)

test_df %>%
     summarise(y = mean(!! rlang::sym(string_outcome)))

或者使用 summarise_at 可以在 vars 参数中接受字符串

test_df %>%
    summarise_at(vars(string_outcome), list(y = ~  mean(.)))

或者如果我们需要没有任何属性的单个值,甚至可以使用 pullmean

test_df %>% 
       pull(string_outcome) %>%
       mean