我已经了解到通常的做法是在函数中使用可选参数并使用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()中有几个可选参数,我将不得不为每个缺失/不丢失编写一个函数调用 - 所有可选参数的组合.
是否可以通过"缺失",或者其他解决方案适用于此问题?
我在包中使用以下构造,
## two functions in the global environment
funa <- function(x) x^2
funb <- function(x) x^3
## called within a function, fine
fun_wrap <- function(){
lapply(c('funa', 'funb'), do.call, list(x=3))
}
fun_wrap()
[[1]]
[1] 9
[[2]]
[1] 27
Run Code Online (Sandbox Code Playgroud)
但是我只是被这样的事实所困扰:如果函数在不同的(本地)框架中它将无法工作,
## same construct, but the functions are local
fun_wrap1 <- function(){
funa1 <- function(x) x^2
funb1 <- function(x) x^3
lapply(c('funa1', 'funb1'), do.call, list(x=3))
}
## now it fails
fun_wrap1()
##Error in FUN(c("funa1", "funb1")[[1L]], ...) :
## could not find function "funa1"
Run Code Online (Sandbox Code Playgroud)
我试图传递 …