Functions and Errors
tryCatch
Handling Conversion
tryCatch lets a script choose a fallback when an expression warns or errors.
Program
Play the script to see invalid text trigger the warning handler and become a fallback value.
try_catch.R
value <- "12x"
number <- tryCatch(as.numeric(value), warning = function(w) NA)
status <- ifelse(is.na(number), "bad", "ok")
cat(status, "\n", sep = "")
tryCatch
`tryCatch` handles warnings or errors from an expression.
as.numeric
`as.numeric(value)` warns when text is not a clean number.
fallback
The warning handler returns `NA`, then the script labels the row `bad`.