R: Write RasterStack and preserve layer names

谁都会走 提交于 2019-12-02 22:55:45

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.

A bit late but might help someone else looking for a possible solution:

writeRaster(stk, filename=names(stk), bylayer=TRUE,format="GTiff")

I wrote my files as ENVI files and changed the band names in the ENVI header file. The files can now be opened in ENVI and ArcGis and the layer names are preserved.

#write ENVI file (.envi; .hdr; .envi.aux.xml) with automatic layer names
writeRaster(stk, "myStack" , format="ENVI")

#change layer names in ENVI header (.hdr):
n="myStack.hdr"  
x <- readLines(n)
x <- gsub("Band 1,", "one,", x) 
x <- gsub("Band 2,", "two," , x)
x <- gsub("Band 3", "three", x)  
cat(x, file=n, sep="\n") #overwrites the old ENVI header

/edit I just noticed that when the .envi file is imported back into R the layer names are removed again. Same problem in SAGA.

image <- stack("myStack.envi")  
names(image)
#[1] "myStack.1" "myStack.2" "myStack.3"

image = readGDAL("myStack.envi") 
names(image)
#[1] "band1" "band2" "band3"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!