Skip to content
Prev 132823 / 398502 Next

Conditionally incrementing a loop counter: Take 2

Since I didn't want the i to increment in the loop when the condition is not met, then in my example I wanted the loop to actually run 14 times instead of the 10 since I wanted 4 of the iterations to be thrown away, or ignored.  I still haven't been able to figure this out.  Going the "while" route doesn't seem to work for me either.


nums <- numeric(10)
i <- 1
garbage <- 0

while (i <= 10){
	x <- runif(1)
	cat("x = ",x,"\n")
	if (x < 0.1){
		nums[i] <- x
		i <- i + 1
	}
	else{
	        garbage <- garbage+1
	}    
cat("i = ",i,"garbage = ",garbage,"\n")
}

-----Original Message-----
From: Peter Dalgaard [mailto:p.dalgaard at biostat.ku.dk] 
Sent: Thursday, December 27, 2007 5:36 PM
To: Mike Jones
Cc: r-help at stat.math.ethz.ch
Subject: Re: [R] Conditionally incrementing a loop counter: Take 2
Mike Jones wrote:
Is this the kind of effect you want?

 > x <- runif(10)
 > cbind(x, 1:10, cumsum(x < .7))
                x    
 [1,] 0.384165631  1 1
 [2,] 0.392715845  2 2
 [3,] 0.895936431  3 2
 [4,] 0.910242185  4 2
 [5,] 0.689987301  5 3
 [6,] 0.237071326  6 4
 [7,] 0.225032680  7 5
 [8,] 0.001856286  8 6
 [9,] 0.392034868  9 7
[10,] 0.655076045 10 8

If you insist on using a loop, you need to separate the loop control 
from the manipulation of i, as in (e.g.)

i <- 0
for (j in 1:10){
   i <- i + 1
   cat("initial i = ",i,"\n")
   x <- runif(1)
   if (x > 0.7){
      i <- i-1
   }   
   cat("second i = ",i,"\n")
}