【问题标题】:R: using ellipsis argument (...)R:使用省略号参数(...)
【发布时间】:2013-06-27 17:36:51
【问题描述】:

我想创建一个包装函数来替换一些默认参数。

这是我正在努力解决的问题的核心:

Error in localWindow(xlim, ylim, log, asp, ...) : 
  formal argument "cex" matched by multiple actual arguments

现在有点上下文。假设我为这样的绘图定义了一个包装函数:

myplot <- function(x, ... ) {
    plot(x, cex= 1.5, ... )
}

如果我打电话给myplot( 1:10, cex= 2 ),我会收到上述错误。我知道我可以将... 转为列表

l <- list(...)

然后我可以做

if( is.null( l[["cex"]] ) ) l[["cex"]] <- 2

但是,我怎样才能将此列表“插入”回省略号参数?类似的东西(我知道这行不通):

... <- l

编辑:我可以在myplot 定义中使用默认值(正如@Thomas 的回答中所建议的那样),但我不想:函数界面会变得混乱。我想我可以定义一个这样的辅助函数:

 .myfunchelper <- function( x, cex= 2.0, ... ) {
   plot( x, cex= cex, ... )
 }

 myfunc <- function( x, ... ) {
    .myfunchelper( x, ... )
 }

但是 (i) 它不那么优雅并且 (ii) 不能满足我的好奇心。

【问题讨论】:

  • 谢谢,非常重要的问题,我现在也在解决这个问题!令人难以置信的是,我在谷歌上搜索“R use argument in ... to override” :-)

标签: r ellipsis


【解决方案1】:

实际答案:

您可以通过一些技巧来做到这一点。首先,像以前一样定义函数,但在函数中包含一个包含默认参数的列表。然后,您可以将通过... 传入的任何参数解析为列表,用... 中的任何内容替换默认值,然后通过do.call 传递更新的参数列表。

myplot <- function(x, ...) {
    args1 <- list(cex=4, main="Default Title") # specify defaults here
    inargs <- list(...)
    args1[names(inargs)] <- inargs
    do.call(plot, c(list(x=x), args1))
}

myplot(x=1:3) # call with default arguments
myplot(x=1:3, cex=2, main="Replacement", xlab="Test xlab") # call with optional arguments

早期评论:

这里的问题可以通过几个示例函数看出:

myplot1 <- function(x, ... ) {
    plot(x, cex= 1.5, ... )
}

myplot2 <- function(x, cex=3, ... ) {
    plot(x, cex=cex, ... )
}

myplot3 <- function(x, ... ) {
    plot(x, ... )
}

myplot1(1:3, cex=3) # spits your error
myplot2(1:3, cex=3) # works fine
myplot3(1:3, cex=3) # works fine

myplot2 中,您指定默认值cex,但可以更改它。在myplot3 中,cex 只是简单地通过。如果您使用两个 cex 参数运行 myplot2,您将看到您的函数 (myplot1) 发生了什么:

myplot2(1:3, cex=3, cex=1.5) # same error as above

因此,您最好避免在plot() 中设置任何默认值,这样您就可以通过... 中的... 传递任何内容myplot

【讨论】:

  • 是的,但这正是我想要避免的。真正的问题很复杂,我不想将默认值放在函数调用定义中——参数已经太多了。
  • 我已根据来自stackoverflow.com/questions/7028385/…的答案进行了更新
  • 非常好的答案。我遇到了同样的错误。我解决了我的问题,根据您的回答更改了椭圆中某些参数的值: param = list(...);成本 = 参数 [[“成本”]];伽玛 = 参数 [[“伽玛”]]; # -> 调整成本和 gamma -> args1
  • 很好的答案(谢谢!),但最好使用args1 &lt;- modifyList(args1, list(...))。因为如果 ... 包含默认 args1 中不存在的一些附加参数,args1[names(inargs)] &lt;- inargs 将不起作用。
猜你喜欢
  • 2011-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-01
  • 2011-03-25
  • 2019-06-28
  • 2021-11-22
  • 2018-01-27
相关资源
最近更新 更多