我有一个想法,在某些迭代中暂停循环并向“用户”询问一些答案。
例如
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”
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
}
}
}
}
对于此类事情使用弹出消息对话框通常会显得更明显且更用户友好。下面我使用 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()
}
如果您有多个 some_criteria 选项(就像我发现这个时所做的那样),请扩展 Paulo MiraMor 的回复
regexpr(question1, 'y', ignore.case = TRUE) == 1
可以替换为
question1 %in% list_of_criteria_conditions
其中 list_of_criteria_conditions 可以类似于
list_of_criteria_conditions <- c("criteria_1", 1, TRUE)