[R] summing elements in a list of functions

James Foadi jf117 at york.ac.uk
Fri Oct 20 16:19:06 CEST 2006


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.

Cheers,

james
-- 
Dr James Foadi
Department of Physics
University of York
York YO10 5DD

email: jf117 at york.ac.uk
web page: http://www-users.york.ac.uk/~jf117
Tel: 0044 1904 434622
Mobile: 0044 7740 678548



More information about the R-help mailing list