【问题标题】:Remove a grouping var in custom function删除自定义函数中的分组变量
【发布时间】:2019-07-15 16:29:18
【问题描述】:

我正在尝试编写一个函数来调整分组变量以排除单个分组变量。该函数始终传递一个分组的 tibble。函数的第一部分在它提供的分组级别进行一些计算。第二部分进行额外的计算,但需要排除在我的数据中动态的单个分组变量。使用 mtcars 作为样本数据集:

library(tidyverse)

# x is a grouped tibble, my_col is the column to peel
my_function <- function(x, my_col){

    my_col_enc <- enquo(my_col)

    # Trying to grab the groups and then peel off the column
    x_grp <- x %>% group_vars()
    excluded <- x_grp[!is.element(x_grp, as.character(my_col_enc))]

    # My calculations are two-tiered as described in the original description
    # simplifying for example
    x %>% group_by(excluded) %>% tally()

}

# This should be equivalent to mtcars %>% group_by(gear) %>% tally()
mtcars %>% group_by(cyl, gear) %>% my_function(cyl)

当我运行它时,我得到一个错误:列“排除”是未知的。

编辑: 对于未来遇到此问题的任何搜索者,如果您有一个字符向量(即多个分组变量),您可能需要使用 syms with !!!实现我最初的问题所要求的。

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    这就是您要查找的内容:

      library(tidyverse)
    
      my_function <- function(x, my_col){
    
        my_col_enc <- enquo(my_col)
    
        # Trying to grab the groups and then peel off the column
        x_grp <- x %>% group_vars()
    
        # here, make sure this is a symbol, else it'll group as character later (e.g. 'gear')
        excluded <- rlang::sym(x_grp[!is.element(x_grp, as.character(my_col_enc))])
    
        # need to use !'s to deal with the symbol
        x %>% group_by(!!excluded) %>% tally()
      }
    

    我评论了代码,但您的第一个问题是无法识别您的 excluded 变量:要对列进行间接引用,有必要在对其进行评估之前修改引用的代码。使用!!(发音为“bang bang”)运算符执行此操作。

    仅将它添加到您的代码中并不能完全解决它,因为excluded 是一个字符。它需要被视为一个符号,因此 rlang::sym() 函数包装了它的声明。

    【讨论】:

    • 我试过了!!起初,但缺少符号处理。感谢您对问题的精彩解释。
    猜你喜欢
    • 2013-01-12
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多