[18906] in s-news-athena

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

[S] rewrite a loop

daemon@ATHENA.MIT.EDU (fan@katan.cybercom.net)
Tue Aug 10 16:11:49 1999

From: fan@katan.cybercom.net
Date: Tue, 10 Aug 1999 15:54:04 -0400
Message-Id: <199908101954.PAA00772@katan.cybercom.net>
To: s-news@wubios.wustl.edu


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