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