2016-05-30 51 views
2

的时候,这里是什么,我希望发生的如何添加默认元素`...`传递这些参数到另一个功能

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=添加默认值,因此写出每个组合都不可行?谢谢!!

回答

2

解决方案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) 

    } 
+0

正是我一直在寻找for..thank你! https://github.com/DjalmaPessoa/convey/commit/4dd0d2d2f36385423e9c03fc6cb2ed51e060fcf9 –

+0

嘿,谢谢你的引用! – Alex

相关问题