Reputation: 61
I have created a program which checks for negative values in the data and then pops up a message that the data contains negative values "do you want to continue or not?" Based on the message box response the program should run further. I want to stop the program if user press No and want to continue in pressed Yes.
How to do this?
Example code:
a <- any(data$time < 0)
if (a == FALSE)
{
require(tcltk)
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")
}
Upvotes: 2
Views: 921
Reputation: 20811
What about readline
instead of a pop-up box?
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
You can also use utils::menu
for a similar function
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
Upvotes: 2
Reputation: 1723
msgBox
can be converted to a character, then you can work on the result as stated below. Feel free to insert any code instead of print()
.
https://stat.ethz.ch/R-manual/R-devel/library/base/html/stop.html
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!")
}
}
This is even simpler:
msgBoxCharacter <- as.character(msgBox)
if(msgBoxCharacter == "no"){
print("flow stops! enter commands here!")
# for example
stop("the user pressed no!")
}
print("flow continues! enter commands here!")
Upvotes: 1