rspatial / terra

R package for spatial data handling https://rspatial.github.io/terra/reference/terra-package.html
GNU General Public License v3.0
543 stars 90 forks source link

`c()` drops SpatRaster layer names #1590

Closed AMBarbosa closed 2 months ago

AMBarbosa commented 2 months ago

When we combine SpatRaster layers with c(), they lose their names:

raster1 <- rast(nrows=108, ncols=21, xmin=0, xmax=10, vals = 1)
raster2 <- rast(nrows=108, ncols=21, xmin=0, xmax=10, vals = 2)
rasters <- c(raster1, raster2)
names(rasters)
# "lyr.1" "lyr.1"

Any chance the original layer names could be kept in the output multilayer SpatRaster, even if via an optional argument to c()?

rhijmans commented 2 months ago

The names are kept. Your example shows that, but like this is should be clearer:

library(terra)
#terra 1.7.81
x <- rast(names="a")
y <- rast(names="b")
names(c(x, y))
#[1] "a" "b"

I assume you expected "x" and "y" ("raster1", "raster2" in your example) but these are object names, and that is something entirely different.

AMBarbosa commented 2 months ago

Thanks -- indeed, I was confusing/mixing layer names with object names... Any chance of an option to keep object names instead? It would be useful when combining single-layer rasters with no assigned layer names (other than the default "lyr.1"), which are the most common case in my experience.

rhijmans commented 2 months ago

That is not possible because the original object names are not known by c. But you can provide names to c like this:

names(c(raster1=x, raster2=y))
#[1] "raster1" "raster2"

Or like this

list(D=x, E=x) |> rast()  |> names()
#[1] "D" "E"
AMBarbosa commented 2 months ago

Awesome, thank you! I'm going with rasters <- rast(c(raster1 = raster1, raster2 = raster2))