实际答案:
您可以通过一些技巧来做到这一点。首先,像以前一样定义函数,但在函数内包含一个包含默认参数的列表。然后你可以解析通过传入的任何参数...
作为列表,将默认值替换为...
然后将更新后的参数列表传递给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
In myplot2
,您指定默认值cex
但可以改变它。在myplot3
, cex
就是简单的通过了。如果你跑myplot2
有两个cex
参数,你会看到你的函数发生了什么(myplot1
):
myplot2(1:3, cex=3, cex=1.5) # same error as above
因此,您可能最好避免设置任何默认值plot()
,这样你就可以通过任何东西...
in myplot
.