RE: [R] Summing up matrices in a list

From: Liaw, Andy <andy_liaw_at_merck.com>
Date: Thu 17 Mar 2005 - 04:14:55 EST


Here's a slight variation:

> lst <- list(matrix(1:4, 2, 2), matrix(5:8, 2, 2), matrix(9:12, 2, 2))
> m <- matrix(0, 2, 2)
> m[] <- rowSums(do.call("cbind", lapply(lst, c)))

> m

     [,1] [,2]
[1,] 15 21
[2,] 18 24

This can probably be simplified even more with the `abind' package...

Andy

> From: Dimitris Rizopoulos
>
> try this:
>
> matSums <- function(lis, na.rm=FALSE){
> if(!is.list(lis) || !all(sapply(lis, is.matrix)))
> stop("'lis' must
> be a list containing 2-dimensional arrays")
> dims <- sapply(lis, dim)
> n <- dims[1, 1]
> p <- dims[2, 1]
> if(!all(n == dims[1, ]) || !all(p == dims[2, ])) stop("the
> matrices must have the same dimensions")
> mat <- matrix(unlist(lis), n * p, length(lis))
> matrix(rowSums(mat, na.rm=na.rm), n, p)
> }
> #########
> mylist <- list(matrix(1:6, 2), matrix(7:12, 2))
> matSums(mylist)
>
>
> I hope it helps.
>
> Best,
> Dimitris
>
> ----
> Dimitris Rizopoulos
> Ph.D. Student
> Biostatistical Centre
> School of Public Health
> Catholic University of Leuven
>
> Address: Kapucijnenvoer 35, Leuven, Belgium
> Tel: +32/16/336899
> Fax: +32/16/337015
> Web: http://www.med.kuleuven.ac.be/biostat/
> http://www.student.kuleuven.ac.be/~m0390867/dimitris.htm
>
>
> ----- Original Message -----
> From: "Vicky Landsman" <msvika@mscc.huji.ac.il>
> To: <r-help@stat.math.ethz.ch>
> Sent: Wednesday, March 16, 2005 5:21 PM
> Subject: [R] Summing up matrices in a list
>
>
> > Dear all,
> > I think that my question is very simple but I failed to solve it.
> > I have a list which elements are matrices like this:
> >
> >>mylist
> > [[1]]
> > [,1] [,2] [,3]
> > [1,] 1 3 5
> > [2,] 2 4 6
> >
> > [[2]]
> > [,1] [,2] [,3]
> > [1,] 7 9 11
> > [2,] 8 10 12
> >
> > I'd like to create a matrix M<-mylist[[1]]+mylist[[2]]
> > [,1] [,2] [,3]
> > [1,] 8 12 16
> > [2,] 10 14 18
> >
> > Is there a way to create M without looping?
> > Thanks a lot,
> > Vicky Landsman.
> > [[alternative HTML version deleted]]
> >
> > ______________________________________________
> > R-help@stat.math.ethz.ch mailing list
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide!
> > http://www.R-project.org/posting-guide.html
> >
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
>
>
>



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Thu Mar 17 04:27:39 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:30:50 EST