有没有办法将任意参数传递给函数内的多个命令?以下功能显然不起作用,但我希望它能解释我想要实现的目标。
test = function(x = rnorm(20), y = rnorm(20), ..., ---){
plot(x, y, type = "p", ...)
lines(x, y, ---)
}
目标是能够编写一个创建情节lines
和points
以及polygon
的函数,并且可以为每个命令获取任意参数并将它们传递给相应的命令没有我必须为每个命令显式指定参数。
答案 0 :(得分:3)
这是一种黑客行为:
.. <- "/////" #or anything which won't be used as a valid parameter
f <- function(...){
arguments <- list(...)
if(.. %in% arguments){
i <- which(arguments == ..)
terms <- unlist(arguments[1:(i-1)])
factors <- unlist(arguments[(i+1):length(arguments)])
c(sum(terms),prod(factors))
}
}
然后,例如,
> f(2,3,4,..,7,8,10)
[1] 9 560
您显然可以将该想法扩展到多个...
字段,每个字段都以..
答案 1 :(得分:1)
<强>功能强>
test = function(x = rnorm(20), y = rnorm(20), plot_options = NA, ...){
if (is.na(plot_options) == FALSE){
eval(parse(text = paste0("plot(x, y, ", plot_options, ")")))
} else {
plot(x, y, type = "n")
}
lines(x, y, ...)
}
<强> USAGE 强>
test()
set.seed(42)
m = rnorm(20)
n = rnorm(20)
test(x = m, y = n,
plot_options = "type = 'p', col = 'red', pch = 19, xlab = 'Test Plot', ylab = 'Y-axis'")
<强>功能强>
test2 = function(x = rnorm(20), y = rnorm(20), ..., line_options){
plot(x, y, ...)
if (missing(line_options)) {
lines(x, y)
} else {
do.call(lines, c(list(x = x, y = y), line_options))
}
}
<强> USAGE 强>
par(mfrow = c(2, 2), mar = c(2, 2, 1, 1))
test2(main = 'default')
test2(line_options = list(lty = 2), main = 'line')
test2(col = 'red', main = 'plot')
test2(col = 'red', line_options = list(lty = 2, col = 'blue'), main = 'line and plot')