[R-sig-Geo] Landcover grd/gri Diva files in R

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Mon May 21 00:50:16 CEST 2012


On Sun, May 20, 2012 at 9:39 PM, Agustin Lobo <alobolistas at gmail.com> wrote:
> I confused the grd and the gri files, thanks for pointing it out.
> But the question remains the same. Is there a function to read the
> table with the legend from the grd file or should I make my own?
> The best would be that, in case a couple of grd and gri files is
> present, raster()
> automatically created the table. Currently, I do not think raster()
> reads anything from
> the grd file, but I might be wrong.

 If raster read it, it would probably be present in the @legend slot
(which is where categorical GTiff colour palettes end up) but its
empty.

 Here's a couple of functions to get you started reading in those .grd files:

eqparse = function(s){
  key = gsub("=.*","",s)
  val = gsub("^[^=]*=","",s)
  m = cbind(key,val)
  rownames(m)=key
  m
}

readgrd <- function(f){
lines = readLines(f)
kv = eqparse(lines)
MinValue = as.numeric(kv["MinValue","val"])
MaxValue = as.numeric(kv["MaxValue","val"])

m = list()

for(v in MinValue:MaxValue){
  m[[v]]=kv[paste("Label",v,sep=""),"val"]
}
m
}

Just do m = readgrd("foo.grd") and you'll get back a list of labels
indexed by value. I don't know if you want to decode the colour values
too - they look like 3-byte integers, but the significant order of
red, green and blue isn't known to me.

There may be bugs. I'm not sure how well this will work if the colour
labels don't start at 1, for example. I think it will work, but the
list will start at '2' or whatever.

raster is clearly reading something from the .grd file, because
otherwise it can't tell the resolution of the .gri file. I can't read
it with readGDAL or get the gdal command-line tools to read it, so I'm
guessing raster is being pretty clever already in working out the file
format.

Barry



More information about the R-sig-Geo mailing list