[R] Running cumulative sums in matrices

Eleni Rapsomaniki er339 at medschl.cam.ac.uk
Wed Apr 14 14:18:06 CEST 2010


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
 



More information about the R-help mailing list