2016-05-30 38 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

相關問題