0

I have an infinite loop doing a given operation, but at some point (decided by the user), I want the loop to run an alternative operation. Is this possible in R; to stop a loop and modify a variable upon a user hitting a key?

In the code below, for instance, the variable Change is set to TRUE originally, can I after hitting a key, modify that variable to FALSE...and may be back to TRUE in a later time while the loop runs?

Keep=TRUE

while (Keep==TRUE){

  Change=TRUE
  if (Change==TRUE){
    print ("a")
  } else {
    print ("b")
  }

  Sys.sleep(1)
}
Camilo
  • 153
  • 7
  • 3
    I honestly do not think that interaction with just the R console allows this type of control, though I will be following this to see if somebody else has a good suggestion. For truly real-time (not typed) interaction needs, you may want to consider shiny interfaces, where there is a more reactive notion to how things flow. Perhaps unfortunately, this requires a bit more investment in the R language (and in your "app" or whatever it is), but is likely more suited for something like this. – r2evans Nov 17 '22 at 23:49
  • Some approaches [a or b](https://stackoverflow.com/questions/41936506/r-language-pause-loop-and-ask-user-for-continue), and google `r request user input within loop` presents quite a few results on SOF. – Chris Nov 18 '22 at 13:22
  • The link's first answer uses `readline`, which does not allow asking a question while operating an "infinite loop". The second link answer uses the `tcltk2` package, which is not "console" (it's widgets), and that package has not been updated in 8 years. While I confess that the [youtube video](https://www.youtube.com/watch?v=rvT8XThGA8o) (link from the package docs, that's all) of `svSocket` being demonstrated is cool, I'm not sure it's the right tool for what Camilo is attempting to do. @Chris, did you find something that supports _non-blocking_ reading of user input? – r2evans Nov 18 '22 at 13:33
  • 1
    Now that I know the right 'state' terms to search, `non-blocking`, that will likely further clarify,and as likely say no can do, as you suggest. – Chris Nov 18 '22 at 13:42
  • My `C` and `C++` are blissfully absent, but all that I've found make it a `.C(`, [kbhit](https://stackoverflow.com/questions/38755283/break-loop-with-keyboard-input-r), or [kbhit - Solution 5](https://www.codeproject.com/Questions/5275669/How-can-I-use-input-without-waiting-user-to-give-s), and in any case the above would need to change out of `readline` for reasons you detail. – Chris Nov 18 '22 at 14:03

0 Answers0