Does this do what you want? m1 <- cbind(1:5,1:5,1:5)
m2 <- m1 for(i in 2:ncol(m1)){ m2[,i] <- apply(m1[,1:i],1,sum) } m2 ut <- diag( ncol(m1) ) ut[upper.tri(ut)] <- 1 m3 <- m1 %*% ut m3 all.equal(m2,m3) hope this helps, -- Gregory (Greg) L. Snow Ph.D. Statistical Data Center Intermountain Healthcare greg.s...@imail.org 801.408.8111 > -----Original Message----- > From: r-help-boun...@r-project.org [mailto:r-help-boun...@r- > project.org] On Behalf Of Eleni Rapsomaniki > Sent: Wednesday, April 14, 2010 6:18 AM > To: r-help@r-project.org > Subject: [R] Running cumulative sums in matrices > > > Dear R-helpers, > > I have a huge data-set so need to avoid for loops as much as possible. > Can someone think how I can compute the result in the following example > (that uses a for-loop) using some version of apply instead (or any > other similarly super-efficient function)? > > example: > #Suppose a matrix: > m1=cbind(1:5,1:5,1:5) > > #The aim is to create a new matrix with every column containing the > cumulative sum of all previous columns. > m2=m1 > for(i in 2:ncol(m1)){ > m2[,i]=apply(m1[,1:i],1,sum) > } > m2 > > Many thanks in advance > > Eleni Rapsomaniki > > Research Associate > Strangeways Research Laboratory > Department of Public Health and Primary Care > University of Cambridge > > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting- > guide.html > and provide commented, minimal, self-contained, reproducible code. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.