Skip to content

sum a list of vectors

1 message · Venables, Bill (CMIS, Cleveland)

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