R: Write RasterStack and preserve layer names

kguay picture kguay · Nov 5, 2014 · Viewed 18.8k times · Source

I have a raster stack, stk, consisting of three raster images in R. Here is a simple example

# set up a raster stack with three layers
> library(raster)
> r <- raster(nrows=10,ncols=10)
> r[] <- rnorm(100)
> stk <- stack(r,r,r)

# layer names are set by default
> names(stk)
[1] "layer.1" "layer.2" "layer.3"

I assign names to the raster layers:

# set layer names to "one", "two" and "three"
> names(stk) <- c('one','two','three')

> names(stk)
[1] "one" "two" "three"

When I write the RasterStack to a GeoTiff (multilayered) using:

writeRaster(stk,"myStack.tif", format="GTiff")

The layers are renamed based on the filename (see > names(stk) below).

When I read in the raster stack:

> stk <- stack("myStack.tif")

# the layer names have been set automatically based on the filename
# they should be "one", "two" and "three"
> names(stk)
[1] "myStack.1" "myStack.2" "myStack.3"

Do you know of any way to preserve the layer names when writing RasterStacks in R? I have tried writing the stack to GeoTIFF and NetCDF formats.

Thanks, Kevin

Answer

bleutner picture bleutner · Nov 29, 2014

You can make use of the native raster format:

myRaster <- writeRaster(stk,"myStack.grd", format="raster")

The raster grid format consists of the binary .gri file and the .grd header file. This will preserve your layernames. Note, however, that .gri binary files are not compressed.

If you need to open raster grd files in other programs you will most likely need to write an additional header file. I usually use the ENVI header format to do that.

hdr(myRaster, format = "ENVI")

To open the file from qgis for example you'd select the .gri file (the binary) and it should work.