Message-ID: <28521902-45a2-822f-ff70-ca9e44856cb3@gmail.com>
Date: 2019-02-27T21:05:47Z
From: Duncan Murdoch
Subject: Error trapping in R
In-Reply-To: <FD7AB93F-9088-4DA8-A49D-2AB370D27715@comcast.net>
On 27/02/2019 3:55 p.m., Bernard Comcast wrote:
> What is the recommended way to trap errors in R? My main need is to be able to trap an error and then skip a section of code if an error has occurred. In VB for Excel I used the ?On Error goto .....? construct to do this.
The recommended way is to use tryCatch() around the expression you're
evaluating. A simpler, less flexible alternative is try(). The Excel
version sounds a bit more like try(). You'd use it like this:
value <- try({ x <- 1
y <- someFunction(x)
someOtherFunction(y)
})
if (inherits(value, "try-error")) {
cat ("something went wrong. There's information in value about
what happened.")
} else {
cat ("value is fine, there was no error.")
}
Duncan Murdoch