0

How can I end a for loop if a condition is met inside it?

I want to break a for loop once t = 1 for example, but as of now I am only breaking out of an if statement inside the for loop.

t = 0
x = matrix()
for (i in 1:10){
   if (t == 1){
       break }
   t = t + 0.01
   x[i] = t
}
user3141121
  • 480
  • 3
  • 8
  • 17
  • there is an answer here http://stackoverflow.com/questions/6082655/r-break-for-loop – Alex Jul 08 '14 at 05:23

1 Answers1

4

Assuming that you mean, for (i in 1:101), you won't get a value equal to 1 in the loop because .01 cannot be exactly represented in binary.

With the modified for statement, the 100'th value is not exactly equal to 1:

x[100] - 1
## [1] 6.661338e-16

To break when something "exceeds or equals" another value, you would use >=. That is, modify the test to read if (t >= 1) { break }. In general, you should not use == to compare floating-point numbers.

Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
  • I apologize for setting an arbitrary example that was incorrect. But I think my point is clear. How can I break out of a for loop if a variable exceeds or equals to some value – user3141121 Jul 08 '14 at 05:43
  • 1
    Your code is already correct, it is the example numbers that are wrong. Try it with integers. – JeremyS Jul 08 '14 at 05:53