[R] sum a list of vectors

Sundar Dorai-Raj sundar.dorai-raj at pdf.com
Fri Dec 13 00:02:03 CET 2002


Hi Tsvetan,

"Stoyanov, Tsvetan" wrote:
> 
> 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.
> 

If you are sure all the elements have equal dimension, you can try the
following:

> x=list(a=1:10,b=11:20,c=21:30)
> x
$a
 [1]  1  2  3  4  5  6  7  8  9 10

$b
 [1] 11 12 13 14 15 16 17 18 19 20

$c
 [1] 21 22 23 24 25 26 27 28 29 30

> rowSums(as.data.frame(x))
 1  2  3  4  5  6  7  8  9 10 
33 36 39 42 45 48 51 54 57 60 
> y=list(a=matrix(1:10,2,5),
+        b=matrix(11:20,2,5),
+        c=matrix(21:30,2,5))
> y
$a
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    5    7    9
[2,]    2    4    6    8   10

$b
     [,1] [,2] [,3] [,4] [,5]
[1,]   11   13   15   17   19
[2,]   12   14   16   18   20

$c
     [,1] [,2] [,3] [,4] [,5]
[1,]   21   23   25   27   29
[2,]   22   24   26   28   30

> matrix(rowSums(as.data.frame(x)),nrow(y[[1]]),ncol(y[[2]]))
     [,1] [,2] [,3] [,4] [,5]
[1,]   33   39   45   51   57
[2,]   36   42   48   54   60
> 

Perhaps there's a better way?

Sundar

-- 
Sundar Dorai-Raj
PDF Solutions, Inc.
Dallas TX




More information about the R-help mailing list