我有多个函数处理可能缺少的参数。
e.g。我有
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)
抛出
论证&#34; somearg&#34;缺少,没有默认
在调试过程中,我发现了以下内容:
mainfunction
开头,missing(somearg)
返回TRUE
mytest
,missing(somearg)
返回TRUE
subfunction
中,missing(somearg)
返回FALSE
(!!!!)因此matrix
分支被点击,但实际上,somearg
缺少,因此它失败了......
笏。
答案 0 :(得分:1)
@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
}