对于我提供的玩具示例来说,这个问题可能听起来很愚蠢,但在我面临的实际情况中实际上是有意义的。
承担职能f
例如:
f <- function(x) {
if (missing(x))
"something very nice happens if x is missing"
else
"something else that is also very nice happens if x not missing"
}
有时我需要打电话f
就像f()
但有时带有指定的参数。
一种方法(基于某些条件cond
):
if (cond) f(1) else f()
但这样的构造会变得更加复杂(就像笛卡尔积一样),并且需要额外的参数。因此我想打电话f
这边走:
f(if (cond) 1 else *)
where *
应该是“没什么”。
如果我是所有者f
我可以将其重写为:
f <- function(x = NULL) {
if (null(x))
"something very nice happens if x is null"
else
"something else that is also very nice happens if x not null"
}
and use * = NULL
。不幸的是我不能这样做,所以另一种方式将不胜感激!
附:这是我在 StackOverflow 上的第一个问题:-) D.S.
你可以使用do.call
与alist
:
f <- function(x, y) {
if (missing(x))
"something very nice happens if x is missing"
else
"something else that is also very nice happens if x not missing"
}
helper <- function(x = NULL, y) {
args <- alist(x = , y = y)
if (!is.null(x)) args[["x"]] <- x
do.call(f, args)
}
helper(1, 1)
#[1] "something else that is also very nice happens if x not missing"
helper(NULL, 1)
#[1] "something very nice happens if x is missing"
helper(if (1 > 2) 3, 1)
#[1] "something very nice happens if x is missing"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)