R:在函数中创建函数,将参数作为默认值

时间:2016-08-25 17:27:25

标签: r function lexical-scope

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

&#34; GenerateFunc&#34;创造了所需的功能,但没有通过&#34; params&#34;到&#34; outfunc&#34;作为默认参数:

myfunc <- GenerateFunc("asymp", params = rep(1,4))
myfunc(x = 10)

Error in myfunc(x = 10) : argument "params" is missing, with no default

非常感谢您的指导。

干杯, 内特

2 个答案:

答案 0 :(得分:1)

您尚未将params参数传递给GenerateFunc,作为paramsoutfunc参数的默认值。可能不那么令人困惑(实际上必须避免递归错误)给默认参数赋予不同的名称。我称之为paramsdefault&#39;:

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)
}

答案 1 :(得分:0)

它没有使用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.
}