我目前正在编写一个函数,如果满足条件,我想传递默认参数。如果不满足条件,则不应传递任何参数。我怎样才能实现这个目标? 我用 ifelse 和 NULL 尝试过,就像这个最小的例子一样,但它不起作用:
my_function <- function(.data,
.variable = ifelse("var1" %in% names(.data), "var1", NULL)){
...
}
如果“var1”不是.data的变量名,并且我没有在.variable上传递另一个参数,我想得到一个错误,比如“参数“.variable”丢失,没有默认值”。我的解决方案有效,但我收到其他错误消息。
最佳答案
似乎 ifelse
不喜欢在条件为 FALSE
的情况下将 NULL
作为响应:
ifelse(2 < 1, 1, NULL)
# Error in ans[!test & ok] <- rep(no, length.out = length(ans))[!test & :
# replacement has length zero
# In addition: Warning message:
# In rep(no, length.out = length(ans)) :
# 'x' is NULL so the result will be NULL
这似乎来自于 ifelse
返回的事实
A vector of the same length and attributes (including dimensions and "class") as test and data values from the values of yes or no.
和
If yes or no are too short, their elements are recycled.
在错误消息中看到 rep
以及 length(NULL)
为零的事实似乎是一个很好的证据。因此,您可能想使用,例如
my_function <- function(.data, .variable = if("var1" %in% names(.data)) "var1" else NULL)
is.null(.variable)
my_function("1")
# [1] TRUE
请参阅 ?ifelse
了解其他警告。
关于r - 仅当满足条件时函数的默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53670278/