I have a large raster stack that is a bunch of groups stacked together. The only thing differentiating the groups is the layer name, which consistently starts with the same prefix. I'd like to separate these groups out into separate stacks, based on the layer name. I know I can use subset()
to extract a specific set of layers, based on either the layer number or the name, but this requires me to manually identify each group separately. Is there any way to do this using an index, maybe similarly to how you can use an index for grouping in terra::tapp()
?
library(terra)
#create sample data
s1 <- rast(nrow=4, ncol=3, nlyrs=5)
values(s1) <- runif(ncell(s1) * dim(s1)[3])
names(s1) <- c('m1', 'm2', 'm3', 'm4', 'm5')
s2 <- rast(nrow=4, ncol=3, nlyrs=5)
values(s2) <- runif(ncell(s2) * dim(s2)[3])
names(s2) <- c('n1', 'n2', 'n3', 'n4', 'n5')
s <- c(s1, s2)
#create index of the different layers - can I use this to separate the groups?
lyr_names <- names(s)
idx <- substr(lyr_names, 1, 1)
#manual subset by position
m <- subset(s, 1:5)
n <- subset(s, 6:10)
#manual subset by names
names_m <- lyr_names[grep("m.*", lyr_names)]
names_n <- lyr_names[grep("n.*", lyr_names)]
m <- subset(s, names_m[names_m %in% names(s)])
n <- subset(s, names_n[names_n %in% names(s)])
You can use split
to get a list of SpatRasters. You could transform that to a SpatRasterDataset with sds
x <- split(s, idx)
names(x) <- c("m", "n")
d <- sds(x)
d$n
#class : SpatRaster
#dimensions : 4, 3, 5 (nrow, ncol, nlyr)
#resolution : 120, 45 (x, y)
#extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
#coord. ref. : lon/lat WGS 84 (CRS84) (OGC:CRS84)
#source(s) : memory
#names : n1, n2, n3, n4, n5
#min values : 0.1240697, 0.1576705, 0.1628487, 0.1937806, 0.02563289
#max values : 0.5467692, 0.8332289, 0.7214081, 0.9200571, 0.83903828