【发布时间】:2016-08-25 17:27:25
【问题描述】:
我正在开发一个函数,它返回另一个特定形式的函数(线性或渐近,由“FuncType”参数指示)。我想为要返回的函数的“params”参数分配一个默认值向量。
# FuncType is either "lin" or "asymp"
# params is a numerical vector of parameters (length 3 if FuncType is "lin",
# length 4 if FuncType is "asymp")
GenerateFunc <- function(FuncType = "lin", params) {
# Linear case: m (slope), b (intercept), and err (error)
if (FuncType == "lin") {
outfunc <- function(x, params){
m <- params[1]
b <- params[2]
err <- params[3]
outval <- m*x + b + rnorm(1, 0, err)
return(outval)
}
}
# Asymptotic case: a (slope), b (curvature), c (rate of convergence), and err (error)
if (FuncType == "asymp") {
outfunc <- function(x, params){
a <- params[1]
b <- params[2]
c <- params[3]
err <- params[4]
outval <- (a * x) / (b*x + c) + rnorm(1, 0, err)
return(outval)
}
}
return(outfunc)
}
“GenerateFunc”创建所需的函数,但不将“params”作为默认参数传递给“outfunc”:
myfunc <- GenerateFunc("asymp", params = rep(1,4))
myfunc(x = 10)
Error in myfunc(x = 10) : argument "params" is missing, with no default
非常感谢您的指导。
干杯, 内特
【问题讨论】:
标签: r function lexical-scope