Skip to content
Back to formatted view

Raw Message

Message-ID: <a920a825-e402-339f-0c26-08891866820e@sapo.pt>
Date: 2019-02-27T21:13:40Z
From: Rui Barradas
Subject: Error trapping in R
In-Reply-To: <FD7AB93F-9088-4DA8-A49D-2AB370D27715@comcast.net>

Hello,

You can trap errors with ?try or ?tryCatch.
Example:


result <- vector(mode = "list", length = 5)
for(i in 1:5){
   result[[i]] <- tryCatch(if(i == 3) stop("This is an error") else 2*i + 1,
            error = function(e) e)
}

result

for(i in seq_along(result)) {
   err <- inherits(result[[i]], "error")
   print(err)
}


Hope this helps,

Rui Barradas

?s 20:55 de 27/02/2019, Bernard Comcast escreveu:
> 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.
> 
> Bernard
> Sent from my iPhone so please excuse the spelling!"
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>