我已经了解到通常的做法是在函数中使用可选参数并使用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()中有几个可选参数,我将不得不为每个缺失/不丢失编写一个函数调用 - 所有可选参数的组合.
是否可以通过"缺失",或者其他解决方案适用于此问题?