【问题标题】:Unquoting argument inside of function in R在R中的函数内取消引用参数
【发布时间】:2021-06-14 01:26:38
【问题描述】:

我无法弄清楚为什么我的函数中的 bang-bang 运算符没有取消引用我的 grp 参数。任何帮助将不胜感激!

library(dplyr)

test_func <- function(dat, grp){
  dat %>%
    group_by(!!grp) %>%
    summarise(N =  n())
}

test_func(dat = iris, grp = "Species")

它只是生成整个数据的摘要,而不是按物种分组:

【问题讨论】:

    标签: r dplyr quotes quasiquotes


    【解决方案1】:

    如果我们传递一个字符串,则转换为symbol 并计算 (!!)

    test_func <- function(dat, grp){
     dat %>%
        group_by(!! rlang::ensym(grp)) %>%
        summarise(N =  n(), .groups = 'drop')
     }
    

    -测试

    test_func(dat = iris, grp = "Species")
    # A tibble: 3 x 2
    #  Species        N
    #* <fct>      <int>
    #1 setosa        50
    #2 versicolor    50
    #3 virginica     50
    

    或者另一种选择是使用across

    test_func <- function(dat, grp){
        dat %>%
           group_by(across(all_of(grp))) %>%
           summarise(N =  n(), .groups = 'drop')
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 2019-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多