[18934] in s-news-athena

home help back first fref pref prev next nref lref last post

[S] summary(2): rewrite a loop

daemon@ATHENA.MIT.EDU (fan@katan.cybercom.net)
Fri Aug 13 11:08:08 1999

From: fan@katan.cybercom.net
Date: Fri, 13 Aug 1999 10:59:06 -0400
Message-Id: <199908131459.KAA25447@katan.cybercom.net>
To: s-news@wubios.wustl.edu


Peter Wolf points that the cumsum() can be used to solve the (equi-weighted)
moving average question. It is by far the best solution, better than matrix 
solution and filter() function. Refer to the first summary I posted.

E.G.
 x<-1:1000
 n <- 30
 result3 <- cumsum(x)
 result3 <- diff(c(0, result3), lag = n)/n 

[original question]
----------------
> From: fan@katan.cybercom.net
> Date: Tue, 10 Aug 1999 15:54:04 -0400
> To: s-news@wubios.wustl.edu
> Subject: [S] rewrite a loop
> X-loop: s-news
> 
> 
> In computing a moving average of a sequence, I look for a way not to use
> the loop? Example:
> 
> #x is a sequence of 1000 data points
> x<-1:1000
> #y is the 30-term moving average of x; 
> #i.e.: y[i] <- mean(x[i:(i+29)]), i = 1, ..., 971
> #or in vector form: y <- (x[1:971]+x[2:972]+...+x[30:1000])/30
> #Surely, a loop solves it:
> y <- rep(0,length(x)-30+1)
> for (j in 1:30)
>     y <- y + x[i:(i+970)]
> y <- y/30
> 
> I feel some better codes can work on this job efficiently without using loop. 
> If you have an idea, let me know. Thanks.
> 
> Fan
> 


-----------------------------------------------------------------------
This message was distributed by s-news@wubios.wustl.edu.  To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message:  unsubscribe s-news

home help back first fref pref prev next nref lref last post