2017-01-30 68 views
1

我有一個想法,暫停在一些迭代循環,並要求「用戶」的一些答案。R語言,暫停循環,並要求用戶繼續

例如

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

相關[如何等R按鍵?](http://stackoverflow.com/questions/15272916/how-to-wait-for-a-keypress-in-r)和[用戶輸入R(Rscript和Widows命令提示符)](http://stackoverflow.com/questions/22895370/user-input-in-r-rscript-and-widows-command-prompt)。 – lmo

回答

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