0

I tried the items here but couldn't just get a simple break of a foreach in sequential (not dopar) loop:Is there any way to break out of a foreach loop?

I just want a simple stop or break that stops the loop at the current iteration (i.e. i=3 below) AND STOPS THE LOOP AT i=3:

   library(foreach)
   foreach(i=c(1:10), .errorhandling ='stop')%do%{
      print(i)
      Sys.sleep(2)
      if(i==3){break} #doesn't do anything
      if(i==3){stop("stopped")} #doesn't stop the function but kicks an error notice at the end
    }
Neal Barsch
  • 2,810
  • 2
  • 13
  • 39
  • I don't know `foreach`, but you can easily enough rewrite as a `while` loop without using `break`. – Tim Biegeleisen Nov 20 '19 at 01:31
  • 1
    Foreach is made for parallel execution. You really shouldn't be in the mindset that it starts at the "beginning" and runs sequentially until it hits the end. If that's what you want then a simple for loop should do the trick and match your mindset more closely. – Dason Nov 20 '19 at 01:46
  • Possible duplicate of [Is there any way to break out of a foreach loop?](https://stackoverflow.com/questions/16079882/is-there-any-way-to-break-out-of-a-foreach-loop) – F. Privé Nov 20 '19 at 07:01
  • 1
    I literally put that question in my question and said why its not a dup – Neal Barsch Nov 21 '19 at 01:03

0 Answers0