Re: [R] Avoiding a loop

From: Daniel Malter <>
Date: Fri, 08 Apr 2011 01:04:03 -0700 (PDT)


this response uses the previous responses with an example:

#Assume you have 100 observations


#Simulate a time series of prices

lag.price=c(rpois(1,100),raw.price[1:99]) price=lag.price+error

#Say you want the moving average based on this
#and the four preceding prices
#define the moving average lag


#Create an index vector from MA.lag+1
#(the first time for which you can compute the MA)
#until the end


#Define a function that computes the moving average
#by taking the mean over the observations
#from (x-MA.lag) to x


#apply this function over all rows of the 'index' matrix
#which yields the moving averages


#Now apply the previous solutions
#First, create a T/F vector whether the price is greater
#than the moving average


#Now create an indicator whether the relation between
#price and moving average changes

v1 <- sapply(2:(n-MA.lag),function(i)S[i]!=S[i-1])

#Output a data frame; when True, column 'signal'
#indicates that the system recommends a transaction
data=data.frame(price[(MA.lag+2):n],mov.av[-1],S[-1],v1) names(data)=c('price','moving.average','','signal') data


View this message in context:
Sent from the R help mailing list archive at

______________________________________________ mailing list
PLEASE do read the posting guide
and provide commented, minimal, self-contained, reproducible code.
Received on Fri 08 Apr 2011 - 08:07:54 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 Fri 08 Apr 2011 - 08:10:28 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.

list of date sections of archive