使用 tidyeval tidyr 排除而不是包含收集变量

Excluding rather than including gather variable using tidyeval tidyr

如果我想排除一些得到 "gathered" 的列(OzoneDayMonth),我可以这样做:

tidyr::gather(airquality, key, value, -Ozone, -Day, -Month)

但是在一个函数中,我不清楚该怎么做。这看起来很笨拙,但它有效:

my_gather <- function(col_to_compare) {
  gather_cols = dplyr::setdiff(c("Ozone", "Solar.R","Wind","Temp"), col_to_compare)
  tidyr::gather(airquality, key, value, !! rlang::enquo(gather_cols))
}

my_gather("Ozone")

知道如何以更严格的方式排除列吗?

注意:这是 tidyr 0.7.0

由于 gather()select() 具有相同的语义,因此此问题与 重复。

您可以使用 -one_of(vars),这是推荐的方法。

或者,您可以构造一个否定符号列表,并在 gather() 调用中拼接这些表达式。以下是如何创建符号并将它们包装在对 -:

的调用中
# This creates a list of symbols
syms <- syms(vars)

# This creates a list of calls:
exprs <- map(syms, function(sym) lang("-", sym))

然后您可以使用 !!!:

拼接调用列表
df %>% gather(key, value, !!! exprs)