[R] how to use conditional statements to handle exceptions?
Henrik Bengtsson
hb at maths.lth.se
Tue Mar 9 21:20:16 CET 2004
For R v1.8.0 you can use tryCatch() (it's great) to catch objects of
class 'condition' and just print() them (instead of letting them
generate errors) like this:
for(i in 1:3) {
file <- paste("file", i, ".dat", sep="")
tryCatch({
bb <- read.table(file)
x11()
plot(bb)
dev.off()
}, condition=function(ex) {
print(ex);
})
}
As soon as/if an error is generated, tryCatch() will catch it an call
the condition function, which will print it.
Details:
If the file does not exists when calling read.table() both a warning
and an error is generated. Since warnings are now of class
simpleWarning and (stop) errors are of class simpleError and both
these are subclasses (via the abstract classes 'warning' and 'error',
respectively) of class 'condition', which is the root class of all
exception classes, it is best to catch by using 'condition' above. If
one use 'error=...' instead, warnings will still be shown.
Moreover, a shorter version of the above would be to use
'condition=print'.
Some further comments:
1) Your code is not correct, e.g. "[1:3]".
Please submit example code that is executable!
2) Did you forget sep="" in the paste line?
1) avoid using "=" to assign; or at least be consistent.
Cheers
Henrik Bengtsson
> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch
> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Susan Lin
> Sent: den 9 mars 2004 18:12
> To: r-help at stat.math.ethz.ch
> Subject: [R] how to use conditional statements to handle exceptions?
>
>
> Hello,
>
> I have a problem to handle the following statements.
>
> for(i in [1:3])
> {
> file=paste("file", i, ".dat")
> bb <- read.table(file)
> x11()
> plot(bb)
> dev.off()
>
> }
> When the input .dat file is empty, the program stops
> running and an error message appears. Could someone
> tell me how to handle this exception?
>
> Thanks
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailma> n/listinfo/r-help
> PLEASE
> do read the posting guide!
> http://www.R-project.org/posting-guide.html
>
>
More information about the R-help
mailing list