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.

Reply via email to