I am preparing a package where users have to store functions and their associated arguments in a list
for later use. This is a typical example of how it works:<
You could use alist
s:
parameters <- list(a1 = alist(fun = dnorm,
args = list(mean = 150, sd = 100)),
a2 = alist(fun = dpois,
args = list(lambda = 40)))
#probably better to write a constructor method for parameters objects
x <- 1:100
myfunction <- function(x, var, parameters)
{ f <- function(x) do.call(fun, c(list(x), args))
formals(f) <- c(formals(f), parameters[[var]])
results <- list(var = var,
y = f(x),
parameters = parameters)
class(results) <- "customclass"
return(results)
}
print.customclass <- function(X)
{
cat("Function name:", X$parameters[[X$var]]$fun)
}
myfunction(x, "a1", parameters)
#Function name: dnorm
I'd suggest to define your parameters
argument with the function name, instead of the function itself and retrieve the function in the body of myfunction
through match.fun
:
parameters <- list(a1 = list(fun = "dnorm",
args = list(mean = 150, sd = 100)),
a2 = list(fun = "dpois",
args = list(lambda = 40)))
myfunction <- function(x, var, parameters)
{
results <- list(var = var,
y = do.call(match.fun(parameters[[var]]$fun),
c(list(x), parameters[[var]]$args)),
parameters = parameters)
class(results) <- "customclass"
return(results)
}