[R] How to program an error into an if-then statement

Nordlund, Dan (DSHS/RDA) NordlDJ at dshs.wa.gov
Tue Nov 9 18:20:18 CET 2010


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Dimitri Liakhovitski
> Sent: Tuesday, November 09, 2010 8:56 AM
> To: r-help
> Subject: [R] How to program an error into an if-then statement
> 
> Hello!
> 
> I am running a loop (for a range of dates) and in this loop I am
> reading in different files - based on a date that is part of the file
> name.
> However, for some of the dates, I have no file (no way to know which
> dates). So, when I try to read it in I get an error:
> 
> Error in file(file, "rt") : cannot open the connection
> 
> Question: I'd like to program an if-then statement in my code that
> says something like this:
> 
> myfile<-read.csv(myfilename)
> if "cannot open the connection" - then do X
> 
> What statement should I use under "if"?
> 
> Thanks a lot!
> 
> 

Rather than trying to read a non-existent file and generating an error,  you might want to check if the file exists before trying to read it and take your alternative action if it doesn't exist.  Check out

 ?file.exists

Hope this is helpful,

Dan

Daniel J. Nordlund
Washington State Department of Social and Health Services
Planning, Performance, and Accountability
Research and Data Analysis Division
Olympia, WA 98504-5204




More information about the R-help mailing list