相关疑难解决方法(0)

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

我已经了解到通常的做法是在函数中使用可选参数并使用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
查看次数

do.call指定函数内的环境

我在包中使用以下构造,

## 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)

我试图传递 …

r do.call

6
推荐指数
1
解决办法
879
查看次数

标签 统计

r ×2

arguments ×1

do.call ×1

function-calls ×1