[R] summing elements in a list of functions

2006-10-20 Thread James Foadi
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

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

2006-10-20 Thread Gabor Grothendieck
Try this: L - list(function(x) 1, function(x) x, sin, cos) sumL - function(x) sum(sapply(L, function(f) f(x))) sumL(pi) # pi On 10/20/06, James Foadi [EMAIL PROTECTED] wrote: 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

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

2006-10-20 Thread Peter Dalgaard
James Foadi [EMAIL PROTECTED] 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

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

2006-10-20 Thread jim holtman
will this work for you? t0 - function(x) {1} t1 - function(x) {x} t2 - function(x) {x^2} t3 - function(x) {x^3} t.l - list(t0,t1,t2,t3) t.l [[1]] function(x) {1} [[2]] function(x) {x} [[3]] function(x) {x^2} [[4]] function(x) {x^3} arg.val - 4 # evaluate for 4

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

2006-10-20 Thread Giovanni Petris
Here is one way. To have a vectorized version you need to redefine 't0', though t0 - function(x) {1} t1 - function(x) {x} t2 - function(x) {x^2} t3 - function(x) {x^3} ttt - list(t0,t1,t2,t3) rrr - function(x) sum(sapply(seq(along=ttt), function(i) ttt[[i]](x))) ## vectorized version ttt[[1]]

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

2006-10-20 Thread James Foadi
Many thanks to those who have answered my question. Could I ask Gabor and Peter the meaning of: sum(sapply(ttt,function(f) f(x))) I gather that a mysterious function f(x) is applied to all components of ttt, and sum can act on this modified object. But what is exactly f? And how does the list

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

2006-10-20 Thread Gabor Grothendieck
ttt is a list of functions so each function in ttt is passed in turn to the anonymous function as argument f. On 10/20/06, James Foadi [EMAIL PROTECTED] wrote: Many thanks to those who have answered my question. Could I ask Gabor and Peter the meaning of: sum(sapply(ttt,function(f) f(x)))