# [R] Avoiding a loop

Daniel Malter daniel at umd.edu
Fri Apr 8 10:04:03 CEST 2011

```Hi,

this response uses the previous responses with an example:

#Assume you have 100 observations
n=100

#Simulate a time series of prices
error=rnorm(n,0,3)
raw.price=rpois(n,100)
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
MA.lag=4

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

#Define a function that computes the moving average
#by taking the mean over the observations
#from (x-MA.lag) to x
MA=function(x){mean(price[(x-MA.lag):x])}

#apply this function over all rows of the 'index' matrix
#which yields the moving averages
mov.av=apply(index,1,MA)

#Now apply the previous solutions
#First, create a T/F vector whether the price is greater
#than the moving average
S=price[(MA.lag+1):n]>mov.av

#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','price.greater.ma','signal')
data

HTH,
Daniel

--
View this message in context: http://r.789695.n4.nabble.com/Avoiding-a-loop-tp3435070p3435559.html
Sent from the R help mailing list archive at Nabble.com.

```