r - 如果使用 dplyr 参数不为空,则使用函数参数有条件地添加管道

标签 r dplyr

我有一个带参数的函数 subset默认值为 NULL 。在函数内 if subsetNULL我不想添加条件管道。否则,我想使用 subset 的值管道内:

library(tidyverse)

f <- function(subset = NULL){
  
  iris %>% 
    {if (is.null(substitute(subset))) . else filter(., {{ subset }} < 2.2)}
  
}

f() # gives error posted below
## Desired output: entire iris dataset

f(subset = Sepal.Width) # works
Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
1            5           2          3.5           1 versicolor

但是,使用大括号,{{ subset}} subset = NULL 时评估为时过早并试图过滤 NULL < 2.2 的位置。 f()返回以下错误:

Error: Problem with filter() input ..1.

x Input ..1 must be of size 150 or 1, not size 0.

i Input ..1 is NULL < 2.2.

最佳答案

您应该在函数体中而不是在 if 子句中计算 is.null(substitute(subset)) 。该子句的计算方式与父子句中的计算方式不同(由于 %>% 堆栈管理)。

这有效:

f <- function(subset = NULL){
  isnull <- is.null(substitute(subset))
  iris %>% 
    {if (isnull) . else filter(., {{ subset }} < 2.2)}
}

head( f() )
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa
f(subset = Sepal.Width)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
# 1            5           2          3.5           1 versicolor

关于r - 如果使用 dplyr 参数不为空,则使用函数参数有条件地添加管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67183028/

相关文章:

r - R 中列表的问题

r - 如何捕捉 "need at least two non-NA values to interpolate"

r - dplyr 。和 _no 全局变量 '.' 的可见绑定(bind) _ 包检查中的注意事项

r - split_wider 其中前半部分成为列名称,后半部分成为单元格值

r - 如何根据 R 中的字典将带有代码的 data.frame 映射到字符串

r - 我可以在 R 中写入和访问内存中的文件吗?

javascript - 将 JavaScript 异步和 igraph 代码移植到 R?

r - 有条件删除面板数据

r - 将函数参数传递给 dplyr select

r - Psych Package - 从 fa.poly 函数中提取因子分数