5

i have an idea to pause loop at some iteration and ask "user" for some answer.

for example

some_value = 0
some_criteria = 50
for(i in 1:100)
{
  some_value = some_value + i
  if(some_value > some_criteria)
  {
    #Here i need to inform the user that some_value reached some_criteria
    #I also need to ask the user whether s/he wants to continue operations until the loop ends
    #or even set new criteria
  }
}

Again, I want to pause loop, and ask user if he would like to continue like: "Press Y/N"

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
Demaunt
  • 1,183
  • 2
  • 16
  • 26
  • 2
    Related [How to wait for a keypress in R?](http://stackoverflow.com/questions/15272916/how-to-wait-for-a-keypress-in-r) and [user input in R (Rscript and Widows command prompt)](http://stackoverflow.com/questions/22895370/user-input-in-r-rscript-and-widows-command-prompt). – lmo Jan 30 '17 at 13:01

2 Answers2

3
some_value = 0
some_criteria = 50
continue = FALSE
for(i in 1:100){
  some_value = some_value + i
  print(some_value)
  if(some_value > some_criteria && continue == FALSE){
    #Here i need to infrom user, that some_value reached some_criteria
    print(paste('some_value reached', some_criteria))

    #I also need to ask user whether he wants co countinue operations until loop ends
    #or even set new criteria

    question1 <- readline("Would you like to proceed untill the loop ends? (Y/N)")
    if(regexpr(question1, 'y', ignore.case = TRUE) == 1){
      continue = TRUE
      next
    } else if (regexpr(question1, 'n', ignore.case = TRUE) == 1){
      question2 <- readline("Would you like to set another criteria? (Y/N)")
      if(regexpr(question2, 'y', ignore.case = TRUE) == 1){
        some_criteria <-  readline("Enter the new criteria:")
        continue = FALSE
      } else {
        break  
      }
    }
  }
}
Paulo MiraMor
  • 1,582
  • 12
  • 30
0

It can often appear more visible and more user friendly to use pop-up message dialogues for this kind of thing. Below I use tkmessageBox from tcltk2 package for this. In this example I used break to exit your loop once the condition is met. Depending on your specific use case, it is sometimes preferable to use while loops in this type of situation rather than having to break out of a for loop prematurely.

library(tcltk2)
some_value = 0
some_criteria = 50
continue = TRUE
for(i in 1:100) { 
  some_value = some_value + i
  if(some_value > some_criteria) {
    response <- tkmessageBox(
      message = paste0('some_value > ', some_criteria, '. Continue?'), 
      icon="question", 
      type = "yesno", 
      default = "yes")
    if (as.character(response)[1]=="no") continue = FALSE
  }
  if (!continue) break()
}
dww
  • 30,425
  • 5
  • 68
  • 111