d_e d_e - 3 months ago 11
R Question

automatically add function to function array in R

all the functions receives the same argument, I want to run all the functions on a same data, so I created manually list of functions:

foo_1 <- function(data){
.
.
}

foo_2 <- function(data){
.
.
}

foo_3 <- function(data){
.
.
}


than:
funcs <- c(foo_1, foo_2, foo_3)


the downside of this approach is if I create a new function, say
foo_4
i need to manually add this function to
funcs
vector. is there any way to this kind of think automatically ?

Answer

Let us first put your functions into a file from which to source them back in ...

# creating the source file for the functions 

funcs_text <- 
"
foo_1 <- function(data){}
foo_2 <- function(data){}
foo_3 <- function(data){}
"

fname <- tempfile()
writeLines(funcs_text, fname)

Now we can read in the file via source(). The trick is to first create an new environment (new.env()) where the functions defined in the file are sourced into. This environment is passed to source() via the local argument. Thereafter we transform the environment to an list - et voila.

# reading in file
funcs <- new.env() 
source(fname, local=funcs)
funcs <- as.list(funcs)

Now you can further use your list of functions to do your processing.

# accessing a function

funcs[[1]]
funcs$foo_1
funcs[["foo_1"]]


# calling a function

funcs[[1]]()
funcs$foo_1()
funcs[["foo_1"]]()