如何传递 R 中缺少的参数?
How to pass down a missing argument in R?
我有一个函数在内部调用另一个可能缺少参数的函数。如果我没有为高级函数中的参数定义默认 NULL
值,则会正确传递缺少的参数。但是,在函数文档中,我想通过为其分配默认 NULL
值来明确指出该参数是可选的。
在下面的 MWE 中,我怎样才能让 high.foo2()
更像 high.foo1()
?
low.foo <- function(y = NULL) if(missing(y)) cat ('y is missing') else print(y)
high.foo1 <- function(y) low.foo(y = y)
high.foo1()
# > y is missing
high.foo2 <- function(y = NULL) low.foo(y = y)
high.foo2()
# > NULL
PD1。不是
的副本
捕获参数并检查它是否为 "NULL"
的选项
high.foo2 <- function(y = NULL) {
if(deparse(substitute(y)) == "NULL") low.foo() else low.foo(y = y)
}
-测试
high.foo2()
y is missing
或者可以使用is.null
high.foo2 <- function(y = NULL) {
if(is.null(substitute(y))) low.foo() else low.foo(y = y)
}
high.foo2()
y is missing
我有一个函数在内部调用另一个可能缺少参数的函数。如果我没有为高级函数中的参数定义默认 NULL
值,则会正确传递缺少的参数。但是,在函数文档中,我想通过为其分配默认 NULL
值来明确指出该参数是可选的。
在下面的 MWE 中,我怎样才能让 high.foo2()
更像 high.foo1()
?
low.foo <- function(y = NULL) if(missing(y)) cat ('y is missing') else print(y)
high.foo1 <- function(y) low.foo(y = y)
high.foo1()
# > y is missing
high.foo2 <- function(y = NULL) low.foo(y = y)
high.foo2()
# > NULL
PD1。不是
捕获参数并检查它是否为 "NULL"
high.foo2 <- function(y = NULL) {
if(deparse(substitute(y)) == "NULL") low.foo() else low.foo(y = y)
}
-测试
high.foo2()
y is missing
或者可以使用is.null
high.foo2 <- function(y = NULL) {
if(is.null(substitute(y))) low.foo() else low.foo(y = y)
}
high.foo2()
y is missing