我有一个函数,我希望这个函数在未调用相应参数时忽略应用于过滤器的条件。
例子:
dataset <- data.frame(a = c(1,2,3), b = c(4,5,6))
topcm <- function(data, feat1, feat2) {
data %>% filter(a == feat1 & b == feat2) }
topcm(dataset, 2, 5) #should return only the second line of dataset
topcm(dataset, feat2 = 5) #I want it to return the second line as well, but it will instead give an error. I want it to still be able to filter, ignoring the conditional that isn't specified as an argument.
我知道我可以应用一些“if”来检查参数是否存在并从那里中断或继续,但是如果有很多参数,我需要一个一个地做。有没有简单的方法来做到这一点?
您可以使用变量的默认值来做到这一点。例如,
topcm <- function(data, feat1 = data$a, feat2 = data$b) {
data %>% filter(a %in% feat1 & b %in% feat2) }
想法是这样的: 的默认值feat1
是表达式data$a
,它将是一个向量,其中包含a
作为 传递的任何数据帧的列中的所有值data
。
如果您没有为 指定值feat1
,则将使用默认值,并且a %in% feat1
将始终是TRUE
因为a
和feat1
将是同一件事。
如果您确实指定了一个值,则默认值将被忽略,并且测试将仅TRUE
针对您作为 传入的那些值feat1
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句