[R] sum a list of vectors
Bill.Venables@CMIS.CSIRO.AU
Bill.Venables at CMIS.CSIRO.AU
Fri Dec 13 00:40:04 CET 2002
Tsvetan Sotyanov asks:
> -----Original Message-----
> From: Stoyanov, Tsvetan [mailto:tsvetan.stoyanov at mirant.com]
> Sent: Friday, December 13, 2002 8:46 AM
> To: 'r-help at stat.math.ethz.ch'
> Subject: [R] sum a list of vectors
>
> In Mathematica there is a neat feature, where you can change the head of a
> list from "list" to say "+" and obtain a sum of the list elements.
> I can't find a way to sum a list of vectors of same length or list of
> matrices of the same dimension and was curious if something like that
> exists in R. do.call("+",list) doesn't work because "+" accepts only two
> arguments, I can obviously use loops but this is quite slow and inelegant.
[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.
> Thanks,
> Tsvetan
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> http://www.stat.math.ethz.ch/mailman/listinfo/r-help
More information about the R-help
mailing list