2017-01-30 38 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を使用しました。特定のユースケースに応じて、forループを途中で中断するのではなく、この種の状況でwhileループを使用することが望ましい場合があります。

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() 
} 
関連する問題