【发布时间】:2021-04-20 16:43:01
【问题描述】:
我有一个带有参数subset 的函数,其默认值为NULL。如果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() 返回以下错误:
错误:
filter()输入有问题..1。x 输入
..1的大小必须是 150 或 1,而不是大小 0。我输入
..1是NULL < 2.2。
【问题讨论】: