d_e d_e - 1 year ago 69
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){

funcs <- c(foo_1, foo_2, foo_3)

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

Answer Source

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


# calling a function

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download