r语言 - 如何将默认元素添加到 '..' 将这些参数传递给另一个函数时



这是一个我想要发生的事情的最小可重现示例

myfun <- 
    function( ... ){
        # myfun only passes `...` on to the plot function
        plot( 
            ... ,
            if( !'xlab' %in% names( list( ... ) ) ) xlab = 'mylabel' ,
            if( !'ylab' %in% names( list( ... ) ) ) ylab = 'ylabel' 
        )
    }
# works the way i want: user specified `xlab` and `ylab` so `...` used them
myfun( 1 , 1 , xlab = "new label" , ylab = "another label" )
# fails
myfun( 1 , 1 )
# Error in plot.window(...) : invalid 'xlim' value

由于用户没有指定xlabylab,我希望我的函数使用我设置的默认值。 所以

plot( 1 , 1 , xlab = 'mylabel' , ylab = 'ylabel' )

如果我有很多可能性,比如xlabylab,最聪明的方法是什么? 我可能还想为 title=xlim=ylim= 添加默认值,所以写出每个组合是不可行的? 谢谢!!

解决方案 1

plot 函数创建自己的自定义包装器:

myplot <- function(x, y, xlab = 'mylabel', ylab = 'ylabel', ...){
  plot(x, y, xlab = xlab, ylab = ylab, ...)
}

myfun <- 
  function( ... ){
    # myfun only passes `...` on to the plot function
    myplot(...)
  }

现在,以下调用按照我认为您希望它们工作的方式工作:

myfun(1, 1)
myfun(1, 1,xlab = "new label" , ylab = "another label" )

解决方案 2

您还可以通过以下方式使用 list(...)do.call

myfun <- 
  function( ... ){
    dots = list(...)
    # check whether needed defaults are supplied, if not, supply them.
    if ~grep('xlab', names(dots) ){
      dots$xlab = 'mylabel'
    }        
    if ~grep('ylab', names(dots) ){
      dots$ylab = 'ylabel'
    }

    # myfun only passes `...` on to the plot function
    do.call(plot, dots)
  }

最新更新