[R] read.table : how to condition on error while opening file?

lauramorgana at bluewin.ch lauramorgana at bluewin.ch
Thu Feb 19 19:06:08 CET 2009


Hello Stephane,
here is something you could try, 

filelist <- c("file1.txt", "file2.txt", "file3.txt")
for (i in 1:3) {
tmpList<-try(read.table(filelist[[i]]), silent=TRUE)
if(inherits(tmpList, "try-error"))
{print(paste("error opening file ", filelist[[i]]))
} else {
tmp<-read.table(filelist[[i]])->namelist[[i]]
   }
 }

There is though a problem that I didnt manage to fix, that is: if , suppose, file1.txt exists, file2 doesn't exist 
and file 3 exists,
the dataframe in file 1 will at first be called tmp, but then it will be substituted by the data.frame in file 3...
It is as if you would do:
c(1,2,3,4)->tmp
and then do
c(1,6,7,8)->tmp
the second tmp will substitute the first one...

Hope this helps
Laura
----Messaggio originale----
Da: E.Vettorazzi at uke.uni-hamburg.de
Data: 19.02.2009 17.23
A: "Stephane Bourgeois"<sb20 at sanger.ac.uk>
Copia: <r-help at r-project.org>
Oggetto: Re: [R] read.table : how to condition on error while opening file?

Hi Stephane,
see ?try
hth.


Stephane Bourgeois schrieb:
> Hi,
>
>  
>
> I'm using read.table in a loop, to read in multiple files. The problem
> is that when a file is missing there is an error message and the loop is
> broken; what I'd like to do is to test for the error and simply do
> "next" instead of breaking the loop. Anybody knows how to do that?
>
>  
>
> Example: 
>
>  
>
> filelist <- c("file1.txt", "file2.txt", "file3.txt")
>
>  
>
> for (i in 1:3) {
>
>   if (read.table(filelist[i]) == ERROR LOADING FILE) {
> # this is where I do not know how to write the condition
>
>     print(paste("error opening file ", filelist[i], sep=""))
>
>     next
>
>   } else {
>
>     tmp <- read.table(filelist[i])
>
>   }
>
> }
>
>  
>
>  
>
> Cheers,
>
>  
>
> Stephane
>
>
>
>
>   

-- 
Eik Vettorazzi
Institut für Medizinische Biometrie und Epidemiologie
Universitätsklinikum Hamburg-Eppendorf

Martinistr. 52
20246 Hamburg

T ++49/40/42803-8243
F ++49/40/42803-7790

______________________________________________
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