Skip to content

Correct Syntax for a Loop

4 messages · ebashi, (Ted Harding), Uwe Ligges +1 more

#
I'll appreciate if some one can help me with the
following loop. This is the logic of the loop,
if we have the following data;
x.dif
 .    .
 .    .
102  0.00
103  0.42
104  0.08
105  0.00
106  0.00
107  0.00
108 -0.16
109 -0.34
110  0.00
111 -0.17
112 -0.33
113  0.00
114  0.00
115  0.00
116  0.33
117  0.17
118  0.00 
 .    .
 .    .
I'm trying to find i's where 
  for (i in 2:length(x.dif))
  if (x.dif[i-1]<=0 and x.dif[i]>0 and x.dif[i+2]>0)
  it would return i+2 to me,
How can I turn this to a right format as a loop.(I
can't figure out the syntax)

Cheers,

Sean
#
On 28-Nov-04 ebashi wrote:
In this sort of case you can do it without a loop. The
following code (which as written is specific to the precise
question you have asked) is the sort of thing you can use:

  n<-length(x.dif)
  y2<-x.dif[4:n]
  y0<-x.dif[2:(n-2)]
  y1<-x.dif[1:(n-3)]
  which((y1<=0)&(y0>0)&(y2>0))+3

Hoping this helps,
Ted.


--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861  [NB: New number!]
Date: 28-Nov-04                                       Time: 12:10:00
------------------------------ XFMail ------------------------------
#
ebashi wrote:
Solution to the question:

a) you cannot loop to length(x.dif), x.dif[i+2] does not exist for 
i==length(x.dif).
b) Use && instead of "and" in this case
c) vector operations are much mor

Hint: If you lengthen the vectors appropriately, you can apply the 
comparisons vectorized  rather than in a loop...

Uwe Ligges
#
ebashi <arshia22 <at> yahoo.com> writes:

: 
: I'll appreciate if some one can help me with the
: following loop. This is the logic of the loop,
: if we have the following data;
: > x.df
:     x.dif
:  .    .
:  .    .
: 102  0.00
: 103  0.42
: 104  0.08
: 105  0.00
: 106  0.00
: 107  0.00
: 108 -0.16
: 109 -0.34
: 110  0.00
: 111 -0.17
: 112 -0.33
: 113  0.00
: 114  0.00
: 115  0.00
: 116  0.33
: 117  0.17
: 118  0.00 
:  .    .
:  .    .
: I'm trying to find i's where 
:   for (i in 2:length(x.dif))
:   if (x.dif[i-1]<=0 and x.dif[i]>0 and x.dif[i+2]>0)
:   it would return i+2 to me,
: How can I turn this to a right format as a loop.(I
: can't figure out the syntax)

One way is to convert it to a ts time series so you can use the lag
operator and have everything automatically aligned for you:

x.dif.ts <- ts(x.dif)
bool <- lag(x.dif.ts,-3) <= 0 & lag(x.dif.ts,-2) > 0 & x.dif.ts > 0
time(bool)[bool]