整洁评估:向函数添加参数以防止收集

Ste*_*ted 2 r tidyr tidyeval

我正在尝试构建一个收集(pivot_longer)数据的函数。
在大多数情况下,该函数应收集所提供数据中除一列之外的所有列,但应允许用户在所提供的数据中指定不应收集的其他列。这是用户很少会做的事情,所以参数应该默认为没有额外的列。

我认为我的函数失败了,因为它默认为NULL.

数据:

library(tidyverse)
sample_data <- tibble(
  frame = rep(seq(1:20), 2),
  ID = rep(c(1,2), each = 20),
  a = rnorm(n = 40),
  b = rnorm(n = 40),
  c = rnorm(n = 40))
Run Code Online (Sandbox Code Playgroud)

功能:

a_gather_function <- function(.data, also_dont_gather = NULL) {
  .data %>% 
  tidyr::gather(key, value, -frame, -{{also_dont_gather}})
}
Run Code Online (Sandbox Code Playgroud)

如果我为参数提供一列,则该函数有效 also_dont_gather

sample_data %>% 
  a_gather_function(also_dont_gather = ID) %>% 
  head(5)

# A tibble: 5 x 4
  frame    ID key    value
  <int> <dbl> <chr>  <dbl>
1     1     1 a     -0.626
2     2     1 a      0.184
3     3     1 a     -0.836
4     4     1 a      1.60 
5     5     1 a      0.330
Run Code Online (Sandbox Code Playgroud)

但以默认值失败NULL

sample_data %>% 
  a_gather_function()

 Error in -x : invalid argument to unary operator 
Run Code Online (Sandbox Code Playgroud)

我很确定错误来自评估 to 的函数-NULL,因为以下代码给出了相同的错误:

sample_data %>% 
  tidyr::gather(key, value, -frame, -NULL)

Error in -x : invalid argument to unary operator
Run Code Online (Sandbox Code Playgroud)

您能帮我构建一个函数,允许用户指定不应收集但默认为没有其他列的其他列吗?

Lio*_*nry 5

编辑:此答案已过时,请参阅/sf/answers/4053059951/了解推荐的解决方案。

我在tidyselect 中打开了一个问题。

在此期间,您可以使用引号和所享有的模式,并检查您是否已经捕获的默认NULLquo_is_null()

a_gather_function <- function(.data, also_dont_gather = NULL) {
  also_dont_gather <- enquo(also_dont_gather)

  if (rlang::quo_is_null(also_dont_gather)) {
    tidyr::gather(.data, key, value, -frame)
  } else {
    tidyr::gather(.data, key, value, -frame, -!!also_dont_gather)
  }
}
Run Code Online (Sandbox Code Playgroud)