2013-06-30 108 views
7

我想創建一個包裝函數來替換一些默認參數。R:使用省略號參數(...)

在這裏,問題的核心,我掙扎:

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, ...) 
} 

但(我)這是那麼優雅和(ii)不滿足我的好奇心。

回答

11

一個實際的答案:

你可以通過一個有點掛羊頭賣狗肉的做到這一點。首先,像以前一樣定義你的函數,但在函數內部包含一個帶默認參數的列表。然後,您可以解析通過...作爲列表進入的任何參數,用...中的任何內容替換默認值,然後通過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默認值,但可以改變它。 myplot3cex只是簡單的通過。如果你有兩個cex參數運行myplot2,你會看到你與你的函數(myplot1)發生的事情:

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

所以,你可能最好避免在plot()設置任何默認值,這樣,那麼你可以通過任何東西通過...myplot

+0

是的,但這正是我想要避免的。真正的問題是複雜的,我不想把默認值放在函數調用定義中 - 已經有太多的參數了。 – January

+0

我已經根據以下答案更新:http://stackoverflow.com/questions/7028385/can-i-remove-an-element-in-dot-dot-dot-and-pass-it-on/7028786# 7028786 – Thomas