【发布时间】: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 !!!实现我最初的问题所要求的。
【问题讨论】: