使用可能为空的参数调用函数的条件参数

时间:2015-09-24 15:21:13

标签: r

对于我提供的玩具示例,这个问题可能听起来很愚蠢,但实际上我真正理解这个问题。

假设函数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 *)

*应该是&#34;没有&#34;。

如果我是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"
}

并使用* = NULL。不幸的是,我不能这样做,所以另一种方式将非常感激!

P.S。这是我在StackOverflow上的第一个问题:-) D.S。

2 个答案:

答案 0 :(得分:2)

您可以将do.callalist

一起使用
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"

答案 1 :(得分:0)

在@Roland的带领下,我会做......

helper <- function(f, ..., ifmissing=NULL){
    lacked <- setdiff(names(formals(f)), names(list(...)))
    wanted <- names(ifmissing)

    missed <- intersect(lacked,wanted)    
    if (length(missed)){
        ifmissing[[ missed[1] ]]
    } else {
        f(...)
    }
}

这是一个例子。 g是一个您无法修改的函数,但是您有一个在缺少每个参数时要遵循的操作列表。缺少的第一个参数(如果有)确定返回的值。

g <- function(x,y) x^y

helper_g <- function(...){
    cond <- list(
        x = "d'oh, base is missing",
        y = "gah, exponent is missing"
    )
    helper(g, ..., ifmissing=cond)
}

helper_g(x=2,y=3) # 8
helper_g(y=3)     # "d'oh, base is missing"
helper_g(x=2)     # "gah, exponent is missing"
helper_g()        # "d'oh, base is missing"

(我意识到这与OP所面临的问题不完全相同,f已经有了处理缺失参数的内部规则。)