相关疑难解决方法(0)

在R函数中指定可选参数的"正确"方法

我感兴趣的是在R中使用可选参数编​​写函数的"正确"方法是什么.随着时间的推移,我偶然发现了几条代码在这里采取了不同的路径,我找不到合适的(官方)位置关于这个话题.

到目前为止,我已经写了这样的可选参数:

fooBar <- function(x,y=NULL){
  if(!is.null(y)) x <- x+y
  return(x)
}
fooBar(3) # 3
fooBar(3,1.5) # 4.5
Run Code Online (Sandbox Code Playgroud)

如果仅x提供,该函数只返回其参数.它使用NULL第二个参数的默认值,如果该参数恰好不是NULL,则该函数会添加两个数字.

或者,可以像这样编写函数(其中第二个参数需要通过名称指定,但也可以使用unlist(z)或定义z <- sum(...)):

fooBar <- function(x,...){
  z <- list(...)
  if(!is.null(z$y)) x <- x+z$y
  return(x)
}
fooBar(3) # 3
fooBar(3,y=1.5) # 4.5
Run Code Online (Sandbox Code Playgroud)

我个人更喜欢第一个版本.但是,我可以看到两者的好坏.第一个版本不太容易出错,但第二个版本可用于合并任意数量的选项.

是否有一种"正确"的方式来指定R中的可选参数?到目前为止,我已经确定了第一种方法,但两者偶尔会感觉有点"hacky".

r function

151
推荐指数
6
解决办法
10万
查看次数

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

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

标签 统计

r ×2

arguments ×1

function ×1

function-calls ×1