Skip to content
Prev 26263 / 398502 Next

sum a list of vectors

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.