[R] A function which is a sum of other functions...

William Dunlap wdunlap at tibco.com
Thu Dec 19 20:58:26 CET 2013


> >> List <- list(abs, function(x)x*10, function(x)x*100)
> >> f <- function(x)Reduce(`+`, lapply(List, function(func)func(x)))
> >> f(-1:2)
> > [1] -109    0  111  222

In that formulation lapply() applies each function in List to x, returning a list of vectors
containing the results (run it outside of Reduce to see this).  Reduce then adds those vectors together.

You can have Reduce evaluate the functions in List and sum the results without using
lapply.  This saves the memory it would take to have all the result vectors in memory
at once, but I find the syntax hard to remember.  
   > g <- function(x)Reduce(function(runningSum, func)runningSum + func(x), List[-1], init=List[[1]](x))
   > g(-1:2)
   [1] -109    0  111  222

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com


> -----Original Message-----
> From: Onur Uncu [mailto:onuruncu at gmail.com]
> Sent: Thursday, December 19, 2013 11:43 AM
> To: William Dunlap
> Subject: Re: [R] A function which is a sum of other functions...
> 
> Thanks William. May I please ask why we needed to use lapply inside Reduce? It sounds
> like we took a list of functions and recreated the same list using lapply. So I couldnt
> follow why we did that...
> 
> Sent from my iPhone
> 
> On 19 Dec 2013, at 19:23, William Dunlap <wdunlap at tibco.com> wrote:
> 
> >> List <- list(abs, function(x)x*10, function(x)x*100)
> >> f <- function(x)Reduce(`+`, lapply(List, function(func)func(x)))
> >> f(-1:2)
> > [1] -109    0  111  222
> >
> > Bill Dunlap
> > Spotfire, TIBCO Software
> > wdunlap tibco.com
> >
> >
> >> -----Original Message-----
> >> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On
> Behalf
> >> Of Onur Uncu
> >> Sent: Thursday, December 19, 2013 11:05 AM
> >> To: r-help at r-project.org
> >> Subject: [R] A function which is a sum of other functions...
> >>
> >>
> >> Dear R Users
> >>
> >> I have a list of functions. Each function in the list is a function of single variable. I
> would
> >> like to create a function (of one variable) which represents the sum of all the functions
> in
> >> the list. So, if the functions in my list are f1(x),..,f5(x) then I would like a new function
> >> f(x)=f1(x)+f2(x)+...f5(x)
> >>
> >> Appreciate any suggestions on how to do this.
> >>
> >> I need the above f(x) function because I would like to minimise it with respect to x
> using
> >> the nlm function.
> >>
> >> Thanks.
> >> ______________________________________________
> >> R-help at r-project.org mailing list
> >> https://stat.ethz.ch/mailman/listinfo/r-help
> >> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> >> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list