-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
project.org] On Behalf Of Newbie1234
Sent: Tuesday, March 26, 2013 7:06 AM
To: r-help at r-project.org
Subject: Re: [R] Newbie code to count runs of up or down moves
I hope this text does not come out unreadable as before. It is
readable in R Studio.. What I am trying to do is take a time-series of
prices and create a histogram of the run lengths, where a run is a
sequence of all up moves or all down moves.
Arun of length k is sequence of k moves all in the same direction
followed by a move in the opposite direction.
To do this I first difference the time series.
Two first differences of the same sign followed by a first difference
of opposite sign is a run length 2.
The outer loop is on the run length denoted by k. The middle loop is
over the date the run starts denoted by i. The inner most loop is on
dates from date i +1 through date i + k. indexed by j.
At each j , I test to see if the price change at date j has the same
sign as that on date j-1. If after testing that the run has a length
of at least k and that is not more than k to determine if starting on
date i there was a run that was exactly of length k, then I increment
y[k].
********************************
The code follows, then after the next ********, is the output with
error messages.
z<-c(3,1,4,5,2,1,0,3,5,8)
z
length(z)
y<-c(0,0,0,0,0,0,0,0,0,0)
y
length(y)
zdiff = diff(z)
zdiff
n<-length(zdiff)
n
x<-zdiff
f<-function(x,y)
{
for (k in 1:n){
for (i in 1:n-k){
endOfRun<-FALSE
anotherRunStep<-TRUE
if(i == (n-k)) endofrun<-TRUE
else if(x[i+k+1]*x[i+k] > 0) endOfRun<-FALSE
for(j in i+1:i+k){
if ((x[j] * x[j-1] < 0){
anotherRunStep<-FALSE
break
} # endif
} # endforj
if (endOfRun && anotherRunStep) y[k]<-y[k]+1
} # endfori
} #e endfork
return(y)
}
f(x,y)
************************
[1] 3 1 4 5 2 1 0 3 5 8
y<-c(0,0,0,0,0,0,0,0,0,0)
y
[1] -2 3 1 -3 -1 -1 3 2 3
x<-zdiff
f<-function(x,y)
+ {
+ for (k in 1:n){
+ for (i in 1:n-k){
+ endOfRun<-FALSE
+ anotherRunStep<-TRUE
+ if(i == (n-k)) endofrun<-TRUE
+ else if(x[i+k+1]*x[i+k] > 0) endOfRun<-FALSE
+ for(j in i+1:i+k){
+ if ((x[j] * x[j-1] < 0){
Error: unexpected '{' in:
" for(j in i+1:i+k){
if ((x[j] * x[j-1] < 0){"
anotherRunStep<-FALSE
break
Error: no loop for break/next, jumping to top level
Error: unexpected '}' in " }"
Error: unexpected '}' in " }"
if (endOfRun && anotherRunStep) y[k]<-y[k]+1
Error: object 'endOfRun' not found
Error: unexpected '}' in " }"
Error: unexpected '}' in " }"
Error: no function to return from, jumping to top level
Error: unexpected '}' in "}"
[1] 6 5 6 5 5 6 5 6 0 0
--
View this message in context: http://r.789695.n4.nabble.com/Newbie-
code-to-count-runs-of-up-or-down-moves-tp4662423p4662459.html
Sent from the R help mailing list archive at Nabble.com.