[R] Running cumulative sums in matrices

Greg Snow Greg.Snow at imail.org
Wed Apr 14 21:05:04 CEST 2010


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.snow at imail.org
801.408.8111


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Eleni Rapsomaniki
> Sent: Wednesday, April 14, 2010 6:18 AM
> To: r-help at 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 at 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.



More information about the R-help mailing list