我有一个带参数的函数 subset
默认值为 NULL
。在函数内 if subset
是 NULL
我不想添加条件管道。否则,我想使用 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
isNULL < 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/