r - 如果 dplyr 的参数不为空,则使用函数参数有条件地添加管道
问题描述
我有一个函数,其参数subset
的默认值为NULL
. 在函数 if subset
isNULL
我不想添加条件管道。否则,我想使用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 = NULL
NULL < 2.2
f()
错误:
filter()
输入有问题..1
。x 输入
..1
的大小必须为 150 或 1,而不是 0。i 输入
..1
是NULL < 2.2
。
解决方案
这是一种在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
推荐阅读
- php - 带有可变变量的 PHP INI 数组
- machine-learning - 学习 Sin 函数
- javascript - 我无法从 React JS 获得 ReactDOM.render?
- javascript - 如何循环遍历一组值以优化对函数的调用次数?
- ios - 不调用约束协议扩展中的函数实现
- mysql - 向 WordPress 元表添加索引是个坏主意吗?
- vba - 如何使用 VBA 仅对包含数据的某些单元格进行数字格式化
- git - git rebase --interactive 只显示最近的两次提交
- reactjs - 我在哪里可以找到 react proptypes 警告的来源?
- ios - 如何使用 Flutter 打开 iPhone 上的默认电子邮件应用程序?