[R] Alternative to For Loop?

From: tom soyer <tom.soyer_at_gmail.com>
Date: Tue, 11 Dec 2007 05:17:35 -0600


Hi,

I am doing a calculation on a long series using a For Loop. Here is an example of the calculation:

accumulate=function(x){
 y=0
 z=0
 for(i in 1:length(x)){
  y=y+x[i]
  z=c(z,y)

 }
 return(z[2:length(z)])
}

> x=c(1:10)
> x


 [1] 1 2 3 4 5 6 7 8 9 10
> accumulate(x)

 [1] 1 3 6 10 15 21 28 36 45 55
>

Although the For Loop works, looping through an array is time consuming and inefficient when the series is large. Does anyone know a faster way of doing the same calculation? Thanks!

-- 
Tom

	[[alternative HTML version deleted]]

______________________________________________
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.
Received on Tue 11 Dec 2007 - 11:39:03 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 11 Dec 2007 - 12:30:17 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.