【发布时间】:2019-10-15 22:44:33
【问题描述】:
我正在尝试使用一组默认值以及通过使用 plot 函数在点 (...) 参数中接受的任何参数来更改这些值的灵活性来创建一个绘图函数。一个例子:
PlotIt <- function(x, y, ...) {
plot(x, y, type = "l", asp = 1, ...)
}
x <- 1:10
y <- 10:1
PlotIt(x = x, y = y)
# Returns a plot
PlotIt(x = x, y = y, asp = NA)
# Error in plot.default(x, y, type = "l", asp = 1, ...) :
# formal argument "asp" matched by multiple actual arguments
错误自然是因为我尝试将asp参数两次传递给plot。到目前为止,我最好的笨拙尝试是做一个 if-else 语句来考虑这一点(该方法是从 here 修改的):
PlotIt2 <- function(x, y, ...) {
mc <- match.call(expand.dots = FALSE)
if(names(mc$...) %in% "asp") {
plot(x, y, type = "l", ...)
} else {
plot(x, y, type = "l", asp = 1, ...)
}
}
PlotIt2(x = x, y = y, asp = NA)
# works
要使用... 参数设置所有可能的参数,我需要编写一个很长的if-else 语句。 有更优雅的方法吗?
问题与this one 有关,不同之处在于我想自动覆盖... 参数设置的所有参数。
【问题讨论】:
标签: r