[R] sum a list of vectors

Thomas Lumley tlumley at u.washington.edu
Fri Dec 13 19:58:09 CET 2002


On Fri, 13 Dec 2002, Stoyanov, Tsvetan wrote:

> Thanks for the response.  Still, my point is that there isn't a
> straightforward way to do an operation which should be bread and butter
> for a language, that prides itself in its connection to Lisp.
>

It's easy to write a LISP-style implementation

reduce<-function(args, FUN=get("+")){
	if (length(args)==2)
		FUN(args[[1]], args[[2]])
	else
	        FUN(args[[1]], reduce(args[-1], FUN=FUN))

}

but it is fairly inefficient in R (worse than the loop) and won't work for
large lists because of the fairly small R stack.

Unwinding the recursion into a loop is the efficient solution, though I
suppose an internal version of reduce() that hid this from the user might
be considered more elegant.

	-thomas




More information about the R-help mailing list