你可以,但这取决于接收函数如何处理事情:
f2 <- function(three, ...) {
g <- as.list(match.call())
print(sprintf("three (from named args) = %d", three))
if ("five" %in% names(g)) print(sprintf("five (from ...) = %d", g$five))
}
f1 <- function(x, y, ...) {
if (missing(x)) stop("x is missing", call.=FALSE)
if (missing(y)) stop("y is missing", call.=FALSE)
g <- as.list(match.call())
print(sprintf("x = %d", x))
print(sprintf("y = %d", y))
f2(...)
}
f1(1, 2, three=4, five=6)
## [1] "x = 1"
## [1] "y = 2"
## [1] "three (from named args) = 4"
## [1] "five (from ...) = 6"
由于您遇到的问题是 scale_y_continuous(因此是 continuous_scale)抱怨未使用的参数,因此您只能传入它将从 ... 列表中接受的内容。这意味着您的职能需要一些内部工作,但这绝对是可行的:
mygg <- function(data, x, y, ...) {
gg <- ggplot(data=data, aes_(substitute(x), substitute(y)))
# get what geom_point accepts
geom_point_aes <- c("x", "y", "alpha", "colour", "color", "fill", "shape", "size", "stroke")
point_params <- unique(c(geom_point_aes,
names(formals(geom_point)),
names(formals(layer))))
# get what scale_y_continuous accepts
scale_y_params <- unique(c(names(formals(scale_y_continuous)),
names(formals(continuous_scale))))
# get all ... params passed in (if any)
args <- list(...)
if (length(args) > 0) {
# get all the arg names
arg_names <- names(args)
# which ones are left for point
gg <- gg + do.call(geom_point,
sapply(intersect(arg_names, point_params),
function(x) { list(args[[x]]) }))
# which ones are left for scale_y
gg <- gg + do.call(scale_y_continuous,
sapply(intersect(arg_names, scale_y_params),
function(x) { list(args[[x]]) }))
} else {
gg <- gg + geom_point() + scale_y_continuous()
}
return(gg)
}
我不会用 png 来混淆答案,但是如果您运行以下命令,您应该会看到修改后的函数做了什么。
mygg(mtcars, mpg, wt)
mygg(mtcars, mpg, wt, color="blue")
mygg(mtcars, mpg, wt, limits=c(3,4))
mygg(mtcars, mpg, wt, fill="green", color="blue", shape=21, limits=c(3,4), left="over")