[R] sum of unknown number of matrices

Berwin A Turlach berwin at maths.uwa.edu.au
Wed Jun 4 17:33:10 CEST 2008


G'day Shubha,

On Wed, 4 Jun 2008 20:23:35 +0530
"Shubha Vishwanath Karanth" <shubhak at ambaresearch.com> wrote:

> Something like do.call("+",l) is not working...why is this?

Well, as the error message says, "+" is either a unary or a binary
operator, i.e. it takes either one or two arguments, but not more.

> I may not be knowing the number of matrices in the list...

This is perhaps a bit complicated but it works:

R> a=b=c=d=matrix(1:4,2,2)
R> l=list(a,b,c,d)
R> library(abind)  ## may have to install this package first
R> apply(do.call(abind, list(l, along=3)), 1:2, sum)
     [,1] [,2]
[1,]    4   12
[2,]    8   16

HTH.

Cheers,

	Berwin

=========================== Full address =============================
Berwin A Turlach                            Tel.: +65 6515 4416 (secr)
Dept of Statistics and Applied Probability        +65 6515 6650 (self)
Faculty of Science                          FAX : +65 6872 3919       
National University of Singapore
6 Science Drive 2, Blk S16, Level 7          e-mail: statba at nus.edu.sg
Singapore 117546                    http://www.stat.nus.edu.sg/~statba



More information about the R-help mailing list