在函数定义中使用可选参数时,省略号有问题。为了澄清,我定义以下功能:
func1 <- function (x) (x-2)^2
func3 <- function (fun, arg.curve.user){
arg.curve.user$expr <- substitute(func1)
arg.curve.default <- list(col = "blue", n = 1000, main = "This is a test")
arg.curve <- modifyList (arg.curve.default, arg.curve.user)
do.call("curve", arg.curve)
}
# optimizes func1 and call func2 to plot func1
func2 <- function (lb, ub, n.restarts = 5, n.sim = 10, ...){
arg.curve.user <- as.list(substitute(list(...)))
output <- gosolnp(fun = func1, LB = lb, UB = ub, n.restarts = n.restarts,
n.sim = n.sim)$par
func3(fun = func1, arg.curve.user = arg.curve.user)
return(output)
}
通过调用func2,可以优化func1并通过func3调用进行绘制(需要包Rsolnp)。
func2 ( lb = 0, ub = 8, n.restarts = 5, n.sim = 10, n = 200, from = 0, to = 8)
但是假设用户拼错了
n.restarts
并编写了nrestarts
:func2 ( lb = 0, ub = 8, nrestarts = 5, n.sim = 10, n = 200, from = 0, to = 8)
在这种情况下,我希望R实施以下计划以应对
n.restarts
的缺失:将n的默认值(即5)分配给n.restarts作为可选参数
最后声明警告:“ nrestarts”不是图形参数
但这不会发生,R会为n分配n(200)的值。
谁能帮我解决这个问题?
非常感谢
最佳答案
如果用户未提供,则部分匹配n
参数和n.restarts
。取而代之的是,与@Andrie的建议相反(当然会起作用),有一种机制可以让您继续使用参数n
和参数n.restarts
进行操作。技巧是将要匹配的参数恰好放在...
之后。
func2 <- function (lb, ub, ..., n.restarts = 5, n.sim = 10){
writeLines(paste("Value of `n.restarts` is", n.restarts))
arg.curve.user <- as.list(substitute(list(...)))
output <- gosolnp(fun = func1, LB = lb, UB = ub, n.restarts = n.restarts,
n.sim = n.sim)$par
func3(fun = func1, arg.curve.user = arg.curve.user)
output
}
在使用中给出:
> func2 (lb = 0, ub = 8, n.restarts = 2, n.sim = 10, n = 200,
+ from = 0, to = 8)
Value of `n.restarts` is 2 <---- Here!
Iter: 1 fn: 6.926e-15 Pars: 2.00000
Iter: 2 fn: 2.501e-15 Pars: 2.00000
solnp--> Completed in 2 iterations
Iter: 1 fn: 8.336e-16 Pars: 2.00000
Iter: 2 fn: 8.336e-16 Pars: 2.00000
solnp--> Completed in 2 iterations
[1] 2
> func2 (lb = 0, ub = 8, nrestarts = 2, n.sim = 10, n = 200,
+ from = 0, to = 8)
Value of `n.restarts` is 5 <---- Here! Default
Iter: 1 fn: 2.83e-15 Pars: 2.00000
Iter: 2 fn: 2.5e-15 Pars: 2.00000
solnp--> Completed in 2 iterations
Iter: 1 fn: 2.037e-15 Pars: 2.00000
Iter: 2 fn: 2.037e-15 Pars: 2.00000
solnp--> Completed in 2 iterations
Iter: 1 fn: 1.087e-15 Pars: 2.00000
Iter: 2 fn: 1.087e-15 Pars: 2.00000
solnp--> Completed in 2 iterations
Iter: 1 fn: 8.558e-16 Pars: 2.00000
Iter: 2 fn: 8.558e-16 Pars: 2.00000
solnp--> Completed in 2 iterations
Iter: 1 fn: 7.147e-16 Pars: 2.00000
Iter: 2 fn: 7.147e-16 Pars: 2.00000
solnp--> Completed in 2 iterations
[1] 2
Warning messages:
1: In plot.window(...) : "nrestarts" is not a graphical parameter
2: In plot.xy(xy, type, ...) : "nrestarts" is not a graphical parameter
3: In axis(side = side, at = at, labels = labels, ...) :
"nrestarts" is not a graphical parameter
4: In axis(side = side, at = at, labels = labels, ...) :
"nrestarts" is not a graphical parameter
5: In box(...) : "nrestarts" is not a graphical parameter
6: In title(...) : "nrestarts" is not a graphical parameter