[R] Running cumulative sums in matrices

ONKELINX, Thierry Thierry.ONKELINX at inbo.be
Wed Apr 14 14:28:14 CEST 2010

?cumsum can help you

m1 <- cbind(1:5,1:5,1:5)
m2 <- m1
 for(i in 2:ncol(m1)){
m3 <- t(apply(m1, 1, cumsum))
all.equal(m2, m3)


ir. Thierry Onkelinx
Instituut voor natuur- en bosonderzoek
team Biometrie & Kwaliteitszorg
Gaverstraat 4
9500 Geraardsbergen

Research Institute for Nature and Forest
team Biometrics & Quality Assurance
Gaverstraat 4
9500 Geraardsbergen

tel. + 32 54/436 185
Thierry.Onkelinx op inbo.be

To call in the statistician after the experiment is done may be no more than asking him to perform a post-mortem examination: he may be able to say what the experiment died of.
~ Sir Ronald Aylmer Fisher

The plural of anecdote is not data.
~ Roger Brinner

The combination of some data and an aching desire for an answer does not ensure that a reasonable answer can be extracted from a given body of data.
~ John Tukey

> -----Oorspronkelijk bericht-----
> Van: r-help-bounces op r-project.org 
> [mailto:r-help-bounces op r-project.org] Namens Eleni Rapsomaniki
> Verzonden: woensdag 14 april 2010 14:18
> Aan: r-help op r-project.org
> Onderwerp: [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 op 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.

Druk dit bericht a.u.b. niet onnodig af.
Please do not print this message unnecessarily.

Dit bericht en eventuele bijlagen geven enkel de visie van de schrijver weer 
en binden het INBO onder geen enkel beding, zolang dit bericht niet bevestigd is
door een geldig ondertekend document. The views expressed in  this message 
and any annex are purely those of the writer and may not be regarded as stating 
an official position of INBO, as long as the message is not confirmed by a duly 
signed document.

More information about the R-help mailing list