我试图使用一组默认值和使用plot函数在dots (...)参数中接受的任何参数更改这些值的灵活性来创建一个绘图函数。举个例子:
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-the语句(该方法是从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- set语句。有更优雅的方法吗?
这个问题与this one有关,它的不同之处在于,我希望自动覆盖由...参数设置的所有参数。
发布于 2019-05-30 15:53:01
如果只想使用基R,可以将所有内容放在列表中,并根据参数名称删除重复项(确保默认值是最后一个,以便在...中出现时删除它们):
PlotIt <- function(x, y, ...) {
arguments <- list(
x = x,
y = y,
...,
type = "l",
asp = 1
)
arguments <- arguments[!duplicated(names(arguments))]
do.call("plot", arguments)
}如果您不介意依赖于rlang,您还可以使用.homonyms获得相同的功能(并检查绘图的轴号,它在基本R版本和rlang版本之间会有所不同):
PlotIt <- function(x, y, ...) {
require("rlang")
arguments <- rlang::dots_list(
rlang::expr(x),
rlang::expr(y),
...,
type = "l",
asp = 1,
.homonyms = "first"
)
call <- rlang::call2("plot", !!!arguments)
eval(call)
}https://stackoverflow.com/questions/56375503
复制相似问题