我创建了一个程序,用于检查数据中的负值,然后弹出一条消息,指出数据包含负值"您要继续还是不继续?"根据消息框响应,程序应该进一步运行。如果用户按否并希望继续按是,我想停止该程序。
怎么做?
示例代码:
currentString
答案 0 :(得分:2)
readline
而不是弹出框呢?
f <- function(x) {
ok <- if (any(x < 0))
readline('x contains negative values, continue? ') else 'yes'
if (tolower(substring(ok, 1, 1)) != 'y')
return(x)
min(x)
}
f(1:5)
# [1] 1
f(-1:5)
# x contains negative values, continue? YES PLS
# [1] -1
f(-1:5)
# x contains negative values, continue? NO THNK U
# [1] -1 0 1 2 3 4 5
您也可以将utils::menu
用于类似的功能
f <- function(x) {
ok <- if (any(x < 0))
menu(c('Yes','No'), FALSE, 'x contains negative values, continue?') else 1
if (ok == 2)
return(x)
min(x)
}
f(1:5)
# [1] 1
f(-1:5)
# x contains negative values, continue?
#
# 1: Yes
# 2: No
#
# Selection: 1
# [1] -1
f(-1:5)
# x contains negative values, continue?
#
# 1: Yes
# 2: No
#
# Selection: 2
# [1] -1 0 1 2 3 4 5
答案 1 :(得分:0)
false
可以转换为字符,然后您可以按照以下说明处理结果。您可以随意插入任何代码而不是msgBox
。
https://stat.ethz.ch/R-manual/R-devel/library/base/html/stop.html
print()
这更简单:
require(tcltk)
data <- data.frame (
"time" = c(1,2,3)
)
a <- any(data$time < 0)
if (a == FALSE)
{
msgBox <- tkmessageBox(title = "Negative Values",
message = "Data have negative values,do you want to proceed further \n Press YES to proceed according to the program and press NO to stop" , icon = "info", type = "yesno")
msgBoxCharacter <- as.character(msgBox)
if(msgBoxCharacter == "yes"){
print("flow continues! enter commands here!")
} else {
print("flow stops! enter commands here!")
# for example
stop("the user pressed no!")
}
}