in R: turn list of functions into one big function (element-wise sum of functions)

function, list, r

Solution

Here's a functional programming approach where you store your functions in a list.

funs <- c(sin,exp)

bigfun<-function(x,funs){
sum(sapply(funs, function(f) f(x)))}

bigfun(x=10,funs=funs)

Learned this from Hadley Wickham: http://adv-r.had.co.nz/Functional-programming.html#lists-of-functions

**EDIT**To supply multiple values (i.e. different value for each function):

bigfun2<-function(vec,funs){vf<-function(vec,funs){funs(vec)} 
sum(sapply(1:length(vec),function (i) vf(vec[i],funs[[i]])))}

optim(par=initvec,fn=bigfun2,funs=funs)

This assumes you have a list of functions equal to the length of your data vector, where `funs` is your function list and `vec` is your data vector. In the optimization example, just set a vector `initvec` with inital starting values of equal length to `funs`, which is passed as an additional param to `optim`

Problem

I have list of functions, which I would like to add up to one "big" function. Example: ``` funlist=list() funlist[[1]]=exp(x1) funlist[[2]]=sin(x2) ``` Desired outcome: ``` bigfun = exp(x1) + sin(x2) ``` I know for numeric cases one could use `reduce("+", list)`, but what about non-numeric cases as above? Please note: I am looking for a general automated solution, that is, the list of functions may vary (functions itself and length of list/ number of functions), but all functions of the list must be added to one final term in the end. Each function should have its own value that must be provided (e.g. x1 to funlist[[1]], x2 to funlist[[2]] etc). IMPORTANT: the bigfun term is then passed on to an optimizer (optim) to find the best values for each function that maximize the outcome of all functions together. EDIT: I chose the fucntions exp(x1) and sin(x2) for simplicity. The functions are function wrappers themselves, eg function(x) {y1*x + y2*x^2 + y3*x^3} , whereby y1, y2, y3 have been calculated before.

Original source