RE: [R] Summing up matrices in a list

From: John Fox <jfox_at_mcmaster.ca>
Date: Thu 17 Mar 2005 - 03:30:07 EST


Dear Vicky,

Actually, this question was asked before (about a year ago, I think).

Looping turns out to be not so bad a solution; check out the following example (from a short-course that I taught):

# to loop or not to loop?     

    # Example: summing a list of matrices         

matrices <- as.list(1:1000) # reasonable system.time(for (i in 1:1000) matrices[[i]] <- matrix(rnorm(100), 10, 10))

matrices <- list() # problematic
system.time(for (i in 1:1000) matrices <- c(matrices,

                                            list(matrix(rnorm(100), 10,
10))))

S <- matrix(0, 10, 10) # simple
system.time(for (i in 1:length(matrices)) S <- S + matrices[[i]]) S

                        # "clever"

system.time(S <- apply(array(unlist(matrices), dim = c(10, 10, 1000)), 1:2, sum))
S

I hope this helps,
 John



John Fox
Department of Sociology
McMaster University
Hamilton, Ontario
Canada L8S 4M4
905-525-9140x23604
http://socserv.mcmaster.ca/jfox

> -----Original Message-----
> From: r-help-bounces@stat.math.ethz.ch
> [mailto:r-help-bounces@stat.math.ethz.ch] On Behalf Of Vicky Landsman
> Sent: Wednesday, March 16, 2005 11:22 AM
> To: r-help@stat.math.ethz.ch
> 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 Received on Thu Mar 17 03:47:39 2005

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