首页 > 解决方案 > 使用 I 字符串来引用 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,但这也不起作用。我怎样才能解决这个问题?

标签: rdplyrnse

解决方案


因为它是一个字符串,所以将其转换为符号 ( symfrom rlang) 并计算 ( !!)

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

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

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

或者如果我们需要一个没有任何属性的单一值,即使pullwithmean也可以使用

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

推荐阅读