Home > Enterprise >  How to use functionals with a list or vector of functions?
How to use functionals with a list or vector of functions?

Time:07-28

I want to use functionals to calculate different summary statistics onto an data set / simulation.

choose_summary <- function(f) f(1:100)
choose_summary(mean)
choose_summary(median)
choose_summary(max)

Thats an easy example on how this should work. I want to use a list of functions to be applied to the data, but it doesnt work the way I expected it to.

sum_fun_list <- list(mean, max, median)
choose_summary(sum_fun_list [1])

Output: Error in f(1:100) : could not find function "f"

What I tried to to is get a element of the list and use it as input for my function, but that doesnt seem to work. It looks like R doesnt recognize the input as a function. I have no idea how to work around that. I tried different approaches like unlist() or as.function() but nothing seems to do the trick. Any idea how to make this work?

Thanks!

CodePudding user response:

do.call is your friend here.

We can make a list of functions and a vector:

funs <- list(mean,median,max)
my_vec <- list(1:100)

Then use sapply to call any function in funs with the argument my_vec

sapply(funs,do.call,my_vec)

CodePudding user response:

The problem is in the way you're indexing the list of functions. This works:

choose_summary(sum_fun_list[[1]])
[1] 50.5

and so does this:

sapply(sum_fun_list, choose_summary)
[1]  50.5 100.0  50.5

When you index a list using [...], as in sum_fun_list[1] you return a list with one element. When you index a list with [[...]] you get the contents of that element (which is the function in your case).

  • Related