R Errors
An error is a failure that stops a script at once. R reports it with a line that starts with the word Error.
Raising an error with stop
This function calls stop when the age is below 18. Calling it with 15 raises the error shown.
check_age <- function(age) {
if (age < 18) {
stop("too young")
}
return("old enough")
}
check_age(15)An error halts the script
The first line calls a function that does not exist. The error stops the script and the done line never prints.
show_report(3)
print("done")Example
x <- as.numeric("abc")Key points
- An error stops the script at once.
- No line after the failing line runs.
- The error text names the call that failed.
- stop() raises an error with a message you choose.
- A warning lets the script finish.
- A value may turn into NA after a warning.
In this example, the text abc cannot turn into a number. The script ends with no error and the warning reports that NA values appeared.
Note
Error text goes to the error stream and not with the normal output.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What happens when a script hits an error?