-2

got a while loop going, and that's working fine. However I also need to add another condition.

I need the loop to keep going until it satisfies the while loop, but then I also need to add that this can only get repeated x times.

I think you would have to make a for loop to do x times, is it possible to put a while loop in this?

Basically how can I make a loop either reach the goal or stop after x loops??

Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
Bennn
  • 3
  • 1
  • 3
  • 2
    Post a reproducible example. Something that we can run – Nishanth Apr 17 '13 at 14:19
  • By a reproducible example @e4e5f4 means sample data + code that reproduces your problem on our computers. See e.g. http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example or RomanLustrik's answer. – Paul Hiemstra Apr 17 '13 at 14:36
  • Generally I would agree that a reproducible example is the way to go, but in this particular case, the description was enough to sort of explain my reasoning through a short self-constructed example. – Roman Luštrik Apr 17 '13 at 16:19

2 Answers2

8

The expression in while needs to be TRUE for the loop to continue. You can use | or & to add extra conditions. This loop runs 99 times or until sum of random variables is less than 100.

counter <- 0
result <- 0

while(counter < 100 | sum(result) < 100) {
  result <- sum(result, rnorm(1, mean = 5, sd = 1))
  counter <- sum(counter, 1)
}

> result
[1] 101.5264
> counter
[1] 21
Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
  • Thanks a lot, didn't know about '|' really useful. Did it different to this, but still helped me solve it. VEery new to this, so sorry if seems stupid. – Bennn Apr 17 '13 at 15:27
1

Just pass the current iterator value as an argument to your function. That way you can break the recursion if that reaches a particular value.

But why do you have a while loop if you use recursion, for example:

add_one_recursive = function(number) {
   number = number + 1
   cat("New number = ", number, "\n")
   if(number > 10) {
      return(number)
   } else {
      return(add_one_recursive(number))
   }
 }
final_number = add_one_recursive(0) 
New number =  1 
New number =  2 
New number =  3 
New number =  4 
New number =  5 
New number =  6 
New number =  7 
New number =  8 
New number =  9 
New number =  10 
New number =  11 

Does not require an explicit loop at all.

Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149