Search code examples
rfilenamesraster

Writing a raster stack to file with changed names


I changed the names of the 20 layers in my raster stack (Rstack) and then write the newly named stack to file but when I read the file back into R the names are not preserved so if I want to use the file I have to re-stack the rasters each time... Here is my code:

Rstack <- Rstack[[name]] #changing names of layers to match model filenames

writeRaster(Rstack, filename="Rstack.tif", options="INTERLEAVE=BAND", overwrite=TRUE)

Rstack <- raster("Rstack.tif") #read in the stack

But when I try to use the "read-in" stack I get an error that the names do not match the model order names - so I then have to restack and rename if I want to use the stack which takes a long time. Is there something I am missing in writeRaster() that would preserve the names after I change them?


Solution

  • You are correct in saying that writeRaster does not preserve layer names (except with using the "grd" format).

    library(raster)
    s <- stack(system.file("external/rlogo.grd", package="raster")) [[1:2]]
    names(s) <- c("a", "b")
    writeRaster(s, "test.tif", overwrite=TRUE)
    
    b <- brick("test.tif")
    names(b)
    #[1] "test.1" "test.2"
    

    However, it takes little effort to set them again

    names(b) <- c("a", "b")
    names(b)
    #[1] "a" "b"
    

    Or you can save as "grd"

    writeRaster(s, "test.grd", overwrite=TRUE)
    b <- brick("test.grd")
    names(b)
    #[1] "a" "b"
    

    To save names in a tif file, you can instead use terra (the replacement of the raster package)

    library(terra)
    x <- rast(system.file("ex/logo.tif", package="terra"))[[1:2]]   
    names(x) <- c("a", "b")
    r <- writeRaster(x, "test.tif", overwrite=TRUE)
    names(r)
    #[1] "a" "b"