Skip to content

sum a list of vectors

2 messages · Stoyanov, Tsvetan, Thomas Lumley

#
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.

Tsvetan Stoyanov

---------------
From: Bill.Venables at CMIS.CSIRO.AU
To: tsvetan.stoyanov at mirant.com, r-help at stat.math.ethz.ch
Subject: RE: [R] sum a list of vectors
Date: Fri, 13 Dec 2002 09:38:45 +1000

Tsvetan Sotyanov asks:
[WNV]  Actually, a loop is not all that bad (contrary to the popular
prejudice), and the inelegance can be overcome simply by having the right
function available.  How about "psum" for "parallel sum", like pmax and
pmin?

	psum <- function(...) {
	        x <- list(...)
	        s <- x[[1]]
	        for(j in seq(along=x)) s <- s+x[[j]]
	        s
	}

	l <- list(a=1:3, b=2:4, c=3:5)
	> do.call("psum", l)
	[1]  7 11 15

	As a homework exercise you could fix psum so that it works with a
null list of arguments.  Use the "most elegant" way you can think of...

	The solution presented elsewhere using rowSums is probably the best,
though, if you can be sure that you are only dealing with vectors and they
all have the same length.  The advantage of going about it the way outlined
above is that the recycling rule kicks in if you need it, or if you are
dealing with more general arrays the answer has the right shape.

	Bill Venables.
#
On Fri, 13 Dec 2002, Stoyanov, Tsvetan wrote:

            
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