【问题标题】:Use I string to refer to a variable inside dplyr? [duplicate]使用 I 字符串来引用 dplyr 中的变量? [复制]
【发布时间】:2019-06-11 14:36:45
【问题描述】:

假设我有以下数据:

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,但这也不起作用。我该如何解决这个问题?

【问题讨论】:

    标签: r dplyr nse


    【解决方案1】:

    因为它是一个字符串,所以将它转换为符号(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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-12
      • 2011-08-25
      • 1970-01-01
      相关资源
      最近更新 更多