[R-sig-Geo] testing for a valid raster format before reading
Mauricio Zambrano-Bigiarini
mauricio.zambrano at jrc.ec.europa.eu
Fri Jul 27 13:45:13 CEST 2012
On 27/07/12 11:35, Barry Rowlingson wrote:
> On Fri, Jul 27, 2012 at 10:08 AM, Mauricio Zambrano-Bigiarini
> <mauricio.zambrano at jrc.ec.europa.eu> wrote:
>> Dear list,
>>
>> Do you know if there is any way for testing if a file can be read by the
>> 'raster' command of the 'raster' package ?
>>
>> something like:
>>
>> is.raster("myfile.asc") ....
>>
>>
>> I'm asking because I have to read many files within several directories.
>> The filenames of the maps go from XXXXXXXX.001 up to XXXXXX99.999, with
>> some additional files that should be skipped of the reading process
>> (which extension varies from directory to directory, e.g., .csv, .txt,
>> .zip, etc).
>>
>>
>> The error I'm getting now, which appears when trying to get information
>> about the file with 'GDALinfo', is the following:
>>
>>
>> Error in .local(.Object, ...) :
>> `lai.zip' not recognised as a supported file format.
>>
>> 1> traceback()
>> 15: .Call("RGDAL_OpenDataset", as.character(filename), TRUE, silent,
>> PACKAGE = "rgdal")
>> 14: .local(.Object, ...)
>> 13: initialize(value, ...)
>> 12: initialize(value, ...)
>> 11: new("GDALReadOnlyDataset", filename, silent = silent)
>> 10: GDAL.open(fname, silent = silent)
>> 9: GDALinfo(maps.list[i])
>>
>>
>> Thanks in advance for any help,
>
> You can use 'try' to run code and catch errors. See help(try) for more:
>
> for(f in files){
> r = try(raster(f))
> if(inherits(r, "try-error")){
> warning("couldnt read ",f)
> }else{
> print(summary(r))
> }
> }
>
Thanks Barry for your feedback.
Adding the 'silent' argument to 'try' produced the behaviour I wanted:
for(f in files){
r = try(raster(f), silent=TRUE)
if(inherits(r, "try-error")){
warning("couldnt read ",f)
}else{
print(summary(r))
}
}
Length Class Mode
66548 RasterLayer S4
Warning messages:
1: In eval(expr, envir, enclos) : couldnt read LHOAT-AGNPS2012.txt
2: In eval(expr, envir, enclos) : couldnt read SPSO.zip
All the best,
Mauricio
--
====================================================
Water Resources Unit
Institute for Environment and Sustainability (IES)
Joint Research Centre (JRC), European Commission
webinfo : http://floods.jrc.ec.europa.eu/
====================================================
DISCLAIMER:\ "The views expressed are purely those of th...{{dropped:10}}
More information about the R-sig-Geo
mailing list