R:在函数内创建一个函数,将参数作为默认值传递

R: Create a function within a function, passing arguments as defaults

我正在开发一个函数 returns 另一个特定形式的函数(线性或渐近,由 "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

非常感谢您的指导。

干杯, 内特

它不使用 params 作为默认参数,因为你没有告诉它!​​

你只需要这样做——尽管你需要更改名称,将默认参数指定为 params = params 是行不通的。

GenerateFunc <- function(FuncType = "lin", params) {
    defaults <- params

    if (FuncType == "lin") {
        outfunc <- function(x, params = defaults) {
            m <- params[1]
            b <- params[2]
            err <- params[3]
            m*x + b + rnorm(1, 0, err)
        }
    }

    … etc.
}

您尚未将进入 GenerateFuncparams 参数作为 outfuncparams 参数的默认值传递。给默认参数一个不同的名字可能不那么令人困惑(实际上是避免递归错误所必需的)。在这里我称之为'paramsdefault':

GenerateFunc <- function(FuncType = "lin", paramsdefault) {

  # Linear case: m (slope), b (intercept), and err (error)
  if (FuncType == "lin") {
    outfunc <- function(x, params = paramsdefault){
      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 = paramsdefault){
      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)
}