R语言,暂停循环并要求用户继续

时间:2017-01-30 12:56:55

标签: r loops pause

我有个想法在某个迭代中暂停循环并向“用户”询问一些答案。

例如

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
  }
}

同样,我想暂停循环,并询问用户是否愿意继续:“按Y / N”

2 个答案:

答案 0 :(得分:1)

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  
      }
    }
  }
}

答案 1 :(得分:0)

对于这种事情,使用弹出消息对话通常会显得更加明显且更加用户友好。下面我使用tcltk2包中的tkmessageBox。在这个例子中,我使用break在条件满足后退出循环。根据您的具体用例,有时最好在这种情况下使用while循环,而不是过早地突破for循环。

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()
}