[R] Reading multiple text files where some files are empty

Paul p.franklin at niwa.co.nz
Wed Sep 1 01:12:11 CEST 2010


Thanks for the responses. 'Try' seems to be the function that I needed. I had
to adapt the code suggested below because vapply wasn't recognised, but this
seemed to work:

a<-list.files()
x<-lapply(a,function(x){try(read.table(x,colClasses='character'))})
bad <- sapply(x, function(x){inherits(x, "try-error")}) #Identifies the
elements of the list with the try-error i.e. empty files
good<-x[!bad] #Removes the elements identified above
myData<-do.call(rbind, good)

Cheers,
Paul


William Dunlap wrote:
> 
> 
> You could use the try() (or tryCatch()) function
> in lapply().  try(expr) returns the value of the
> expression if there is no error and an object of
> class "try‑error" containing the error message if
> there was an error.  Execution continues normally
> after that.
> 
> E.g.,
>   x<‑lapply(a,function(x){try(read.table(x,colClasses='character'))})
>   # now remove entries corresponding to bad files
>   bad <‑ vapply(x, inherits, "try‑error", FUN.VALUE=logical(1))
>   xgood <‑ x[!bad]  # x[bad] would show you the error messages
>   myData <‑ do.call(rbind, xgood)
> Use try's silent=TRUE argument if you don't want to
> see the error messages while lapply is running.
> 
> Bill Dunlap
> Spotfire, TIBCO Software
> wdunlap tibco.com 
> 
> 

-- 
View this message in context: http://r.789695.n4.nabble.com/Reading-multiple-text-files-where-some-files-are-empty-tp2401035p2402437.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list