我有多个函数来处理可能丢失的参数。

例如我有

mainfunction <- function(somearg) {
    mytest(somearg)
    fun <- function() { subfunction(somearg) }
    fun()
}


有趣的是,mytest(somearg)与arg的唯一交互是它测试参数是否不丢失:

mytest = function(somearg) {
    print(missing(somearg))
}


subfunction然后再次测试是否丢失,并相应地进行处理:

subfunction = function(somearg) {
    if (missing(somearg))
        somearg = NULL
    else
        somearg = matrix(somearg, cols = 2)
    # somearg is used here…
}


更重要的是,缺少somearg时,此操作无效:matrix(somearg, cols = 2)抛出


参数“ somearg”丢失,没有默认值


在调试过程中,我发现以下内容:


mainfunction的开头,missing(somearg)返回TRUE
mytest中,missing(somearg)返回TRUE
subfunction中,missing(somearg)返回FALSE(!!!!)


因此matrix分支被命中,但实际上,somearg丢失了,所以失败了……

at

最佳答案

@BenBolker方式:

mainfunction <- function(somearg = NULL) {
    mytest(somearg)
    fun <- function() { subfunction(somearg) }
    fun()
}

mytest = function(somearg) {
    print(is.null(somearg))
}

subfunction = function(somearg) {
    if (is.null(somearg))
        somearg = 1:10
    else
        somearg = matrix(somearg, ncol = 2)
   somearg
}


另一种方法,使用显式缺少参数

mainfunction <- function(somearg) {
    is_missing <- missing(somearg)
    mytest(is_missing)
    fun <- function() { subfunction(somearg, is_missing) }
    fun()
}
mytest = function(x) {  print(x) }
subfunction = function(somearg, is_arg_missing) {
    if (is_arg_missing)
        somearg = 1:10
    else
        somearg = matrix(somearg, ncol = 2)
   somearg
}


第三种方法,使用普通的缺少arg传递:

    mainfunction <- function(somearg) {
        is_missing <- missing(somearg)
        mytest(somearg)
        fun <- function() {
          if (is_missing) subfunction() else
              subfunction(somearg)
        }
        fun()
    }

    mytest = function(somearg) {
        print(missing(somearg))
    }

    subfunction = function(somearg) {
        if (missing(somearg))
            somearg = 1:10
        else
            somearg = matrix(somearg, ncol = 2)
       somearg
    }

08-24 16:45