我正在尝试编写一个函数来调整分组变量以排除单个分组变量。该功能始终传递分组的小标题。函数的第一部分在提供的分组级别上进行一些计算。第二部分进行其他计算,但需要排除在我的数据中动态的单个分组变量。使用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与!!!一起使用!达到我最初的要求。
答案 0 :(得分:0)
这就是您要寻找的东西:
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()
函数会包装其声明。