user8333220
user8333220

Reputation: 69

Skipping iterations in a for-loop

I tried to skip some iterations in a for loop:

Lines <- "
 time   Temperature
  1         38.3
  2         38.5
  3         38.9
  4         40.1
  5         38.0
  6         38.6
  7         37.9
  8         38.2
  9         37.5
  10        38.0"
DF <- read.table(text = Lines, header = TRUE)

for (i in unique(DF$time)){
 ix=which(i==DF$time)
 if(DF$Temperature[ix] > 38.65)  ix=ix+3
 print(ix)
}

But I don't get the desired output. It is not skipping the iterations. Instead it just overwrites it so that I get some iterations twice.

Output:

[1] 1
[1] 2
[1] 6
[1] 7
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

Desired output:

[1] 1
[1] 2
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

Update:

i=1
while(i<=DF$time){
  if(DF$Temperature[i] > 38.65){  
    print(i)
    i=i+3}
    i=i+1
}

That is what I tried. But obviously its wrong. Never used while before. Can someone help me?

Upvotes: 0

Views: 755

Answers (2)

JineshEP
JineshEP

Reputation: 748

As per your input, only the 3rd and 4th index has the DF$Temperature > 38.65 comparison giving tru result, rest is false.

The R comparison 38.6 > 38.65 will give a result equal to false.

So,

   DF$Temperature > 38.65
   [1] FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE

So your output is according to the logic here, the 3rd and 4th index is incremented by 3.

[1] 1
[1] 2
[1] 6 # index3 +3
[1] 7 # index 4 +3
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

Upvotes: 0

David Klotz
David Klotz

Reputation: 2431

I think you're confusing for vs. while clauses in R. This does basically what you're trying to do:

ix <- 1
while(ix <= 10) {
  if (DF$Temperature[ix] > 38.65) {
    ix = ix + 3
    print(ix)
  } else{
    print(ix)

  }
  ix = ix + 1
}

edited with @jogo's correction

Upvotes: 2

Related Questions