I am writing a function in R and managing error handling (I specifically added few warning messages).
I am wondering if there is there a way to create a question "Do you want to continue?" that would pop up in R Console each time a warning appears? In order to proceed the user would have to type "Y" (yes) in the console. Something similar to swirl functionality.
The goal is to make sure user saw the warning message and consciously wants to continue.
Any hint would be much appreciated. Thank you!
CodePudding user response:
You can use tryCatch
.
Suppose I want to convert character strings to numbers. Ordinarily, if a character vector contains some strings that can't be coerced into numbers, then calling as.numeric
on the vector will proceed without error, but will emit a warning saying that NA
values have been introduced by coercion.
If I want more control over this process by being explicitly asked whether to go ahead with the conversion when NAs are going to be produced by coercion, then I could do:
convert_to_numeric <- function(x) {
tryCatch({
as.numeric(x)
},
warning = function(w) {
cat("Warning!", w$message, '\n')
cont <- readline('Do you wish to continue? [Y/N] ')
if(cont != 'Y') stop('Aborted by user')
return(suppressWarnings(as.numeric(x)))
}
)
}
Which results in the following behaviour:
convert_to_numeric(c('1', '2', '3'))
#> [1] 1 2 3
convert_to_numeric(c('1', '2', 'banana'))
#> Warning! NAs introduced by coercion
Do you wish to continue? [Y/N] Y
#> [1] 1 2 NA
convert_to_numeric(c('1', '2', 'banana'))
#> Warning! NAs introduced by coercion
Do you wish to continue? [Y/N] N
#> Error in value[[3L]](cond) : Aborted by user