[SOLVED] How do I define a list/vector of functions in R?


I have a function which takes another function as an input variable, eg.

WrapperFunction <- function(x, BaseFunction){
   y <- cor(x)

Now I want to input various BaseFunctions into this WrapperFunction, to produce a vector of outputs, but how do I define a list of functions so that instead of plugging in each function by hand, I can automate the process with a for loop:

for (i in 1:n){
   output[i] <- WrapperFunction(x, FunctionList[i])

I’ve tried defining

FunctionList <- list()

FunctionList[1] = Function1 , etc....

, which didn’t work.

Nor did defining

FunctionList <- c("Function1", "Function2", ...)


If you want to have a list of functions, you can do something like:

myFuns <- list(mean, sd)

And then you can lapply over this list, or use the for loop as you wanted. If you use the for loop make sure that you use the [[ syntax, because this makes sure that you are retrieving the function and not a length one list:

for (i in 1:n){
    output[i] <- WrapperFunction(x, myFuns[[i]])


lapply(myFuns, WrapperFunction, x = x)

Answered By – thothal

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *