首页 > 解决方案 > 如果 dplyr 的参数不为空,则使用函数参数有条件地添加管道

问题描述

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

但是,使用大括号,在何时以及试图过滤 where{{ subset}}时评估为时过早。返回以下错误:subset = NULLNULL < 2.2f()

错误:filter()输入有问题..1

x 输入..1的大小必须为 150 或 1,而不是 0。

i 输入..1NULL < 2.2

标签: rdplyr

解决方案


这是一种在error发生以下情况时返回完整数据集的方法tryCatch

f <- function(subset = NULL){

  tryCatch(  iris %>% 
    filter({{ subset }} < 2.2)
      , error = function(err) iris)
    

 }

-测试

dim(f())
#[1] 150   5

dim(f(subset = Sepal.Width))
#[1] 1 5

推荐阅读