1

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?

1 Answer 1

2

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"
2
  • grd option worked perfectly but for the last one, saving as tif, since I have 20 layers would I have: [[1:20]] ?
    – BHope
    Apr 5, 2022 at 20:07
  • 1
    You do not need to use [[ ]] ---- that was just for the example to get two layers. Apr 5, 2022 at 20:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.