[R] Help with tryCatch with a for loop
William Dunlap
wdunlap at tibco.com
Thu Nov 10 00:40:41 CET 2011
If your loop is of the form
for(i in 1:n) {
doSomethingSafe()
x <- doSomethingThatFailsSometimes()
doSomethingWithX(x) # cannot do this if previous line fails
doSomethingElseSafe()
}
and you want it to somehow recover when
doSomethingThatFailsSometimes() throws an error,
then change it to use try() with
for(i in 1:n) {
doSomethingSafe()
tmp <- try({
x <- doSomethingThatFailsSometimes()
doSomethingWithX(x)
})
if (inherits(try, "try-error")) {
recoverFromFailure()
}
doSomethingElseSafe()
}
or to use tryCatch() with
for(i in 1:n) {
doSomethingSafe()
tryCatch({
x <- doSomethingThatFailsSometimes()
doSomethingWithX(x)
}, error = function(e) {
message("Had a problem at iteration ", i, ": ", conditionMessage(e))
recoverFromFailure()
})
doSomethingElseSafe()
}
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Spencer S
> Sent: Wednesday, November 09, 2011 2:57 PM
> To: r-help at r-project.org
> Subject: Re: [R] Help with tryCatch with a for loop
>
> My apologies for not including some test data.
> Attached is a sample dataset that fails with the first stateroute and works
> with the second.
>
> http://r.789695.n4.nabble.com/file/n4021696/testdata.csv testdata.csv
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Help-with-tryCatch-with-a-for-loop-
> tp4020475p4021696.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
More information about the R-help
mailing list