[英]Filter argument in function that defaults to make dplyr::filter() filter nothing
I am building a function that imports excel spreadsheets. 我正在构建一个导入excel电子表格的功能。
I would like the function to include an argument that contains names of variables that the user is interested in seeing. 我希望函数包含一个参数,该参数包含用户感兴趣的变量名。 The values from the argument is used in dplyr::filter() inside the function.
该参数的值在函数内部的dplyr :: filter()中使用。 I would like the default value of the argument to include everything (ie not filter anything away).
我希望参数的默认值包括所有内容(即不过滤掉任何内容)。
Libraries and Data: 库和数据:
library(tidyverse)
data("iris")
The filter function without any default filter values (this works): 没有任何默认过滤器值的过滤器功能(有效):
FILTER <- function(data = iris,
Filter_Values) {
data %>%
filter(Species %in% Filter_Values)
}
FILTER(Filter_Values = c("setosa", "virginica"))
As written above, I would like the Filter_Values argument to default into NOT filtering anything. 如上所述,我希望Filter_Values参数默认为不过滤任何内容。
This works, but is of course not general: 这可行,但是当然不是一般的:
FILTER <-
function(data = iris,
Filter_Values = c("setosa", "versicolor", "virginica")) {
data %>%
filter(Species %in% Filter_Values)
}
FILTER()
Can you help me find a general term that can do the same. 您能帮我找到一个可以做到的通用术语吗? I have tried (and failed) with:
我尝试过(但失败了):
Filter_Values = TRUE
Filter_Values = c(TRUE)
Filter_Values = regex(".*")
Filter_Values = everything()
Any help appreciated, 任何帮助表示赞赏,
Thanks 谢谢
How about this? 这个怎么样?
FILTER <-
function(data = iris,
Filter_Values = unique(data$Species)) {
data %>%
filter(Species %in% Filter_Values)
}
FILTER()
Perhaps: 也许:
FILTER <- function(data = iris,Filter_Values = NULL) {
if (missing(Filter_Values)) data
else data %>% filter(Species %in% Filter_Values)
}
FILTER()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.