Nate L - 1 year ago 79
R Question

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

I am developing a function that returns another function of a particular form (linear or asymptotic, indicated by the "FuncType" argument). I would like to assign a vector of default values to the "params" argument of the function to be returned.

``````# 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" creates the desired function but does not pass "params" to "outfunc" as a default argument:

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

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

Many thanks in advance for your guidance.

Cheers,
Nate

It doesn’t use `params` as a default argument because you don’t tell it to!

You just need to do this — you need to change the name though, specifying a default parameter as `params = params` won’t work.

``````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.
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download