Re: [R] summing elements in a list of functions

From: Peter Dalgaard <p.dalgaard_at_biostat.ku.dk>
Date: Fri 20 Oct 2006 - 14:26:37 GMT

James Foadi <jf117@york.ac.uk> writes:

> Dear all,
> I have looked for an answer for a couple of days, but can't come with any
> solution.
>
> I have a set of functions, say:
>
> > t0 <- function(x) {1}
> > t1 <- function(x) {x}
> > t2 <- function(x) {x^2}
> > t3 <- function(x) {x^3}
>
> I would like to find a way to add up the previous 4 functions and obtain a new
> function:
>
> > rrr <- function(x) {1+x+x^2+x^3}
>
> without, actually, having to write it in the previous form (I could have cases
> with hundreds of functions). I thought that perhaps I could first define a
> list of functions:
>
> > ttt <- list(t0,t1,t2,t3)
>
> and then I could use something like "sum", to add up all the elements of the
> list and obtain another function. I've tried:
>
> > rrr <- function(x) {sum(ttt)}
>
> but it does not work.
>
> Any help with this is greatly appreciated.

rrr <- function(x) sum(sapply(ttt,function(f)f(x)))

-- 
   O__  ---- Peter Dalgaard             Ă˜ster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard@biostat.ku.dk)                  FAX: (+45) 35327907

______________________________________________
R-help@stat.math.ethz.ch 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.
Received on Sat Oct 21 05:58:29 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Fri 20 Oct 2006 - 20:30:38 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.