小编Mar*_*usN的帖子

在函数中将缺少的参数从函数传递给函数

我已经了解到通常的做法是在函数中使用可选参数并使用missing()进行检查(例如,如SO 22024082中所述)

在这个例子中,round0是可选参数(我知道,round0可以定义为逻辑).

foo = function(a, round0) {
    a = a * pi
    if(!missing(round0)) round(a)
    else a
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我从另一个函数调用此函数,我怎么能传递"missing"?

bar = function(b) {
    if(b > 10) round1=T
    foo(b, round1)
}
Run Code Online (Sandbox Code Playgroud)

如果b <10,则bar()中的round1未定义,但无论如何都会传递给foo.如果我修改foo():

foo = function(a, round0) {
    a = a * pi
    print(missing(round0))
    print(round0)
    if(!missing(round0)) round(a)
    else a
}
Run Code Online (Sandbox Code Playgroud)

并运行bar(9)输出为:

bar(9)
[1] FALSE
Error in print(round0) : object 'round1' not found
Called from: print(round0)
Run Code Online (Sandbox Code Playgroud)

这意味着:round0没有丢失,但也无法访问?

我不想在bar()中使用不同的函数调用,如果foo()中有几个可选参数,我将不得不为每个缺失/不丢失编写一个函数调用 - 所有可选参数的组合.

是否可以通过"缺失",或者其他解决方案适用于此问题?

arguments r function-calls

14
推荐指数
2
解决办法
7250
查看次数

标签 统计

arguments ×1

function-calls ×1

r ×1