Subset spatRaster layers; return layers that match subset names, ignore those that do not?

Advertisements

I’m looping through rasters and would like to select a subset of layers if they match certain layer names that I’m looking for. When using terra::subset, an error will occur if a layer name is specified that does not exist in the raster. Is there a way to just return layer names that match and ignore those that do not?

This throws an error but I’d like it to just return layer "A"

library(terra)
r1 <- rast(matrix(1:100, nrow=10, ncol=10))
r2 <- rast(matrix(200:101, nrow=10, ncol=10))
r3 <- rast(matrix(c(2,200), nrow=10, ncol=10))
s <- c(r1,r2,r3)
names(s) <- c("A","B","C")
print(s)
s2<-subset(s,c("A","D"))

Error: [subset] invalid name(s)

>Solution :

You can try this small variation:

ind <- match(c("A","C"), names(s))
ind <- ind[!is.na(ind)]

s[[ names(s)[ind] ]] # OR
terra::subset(s, names(s)[ind])

Following your example:

library(terra)
r1 <- rast(matrix(1:100, nrow=10, ncol=10))
r2 <- rast(matrix(200:101, nrow=10, ncol=10))
r3 <- rast(matrix(c(2,200), nrow=10, ncol=10))
s <- c(r1,r2,r3)
names(s) <- c("A","B","C")
print(s)

ind <- match(c("A","C"), names(s))
ind <- ind[!is.na(ind)]


> s[[ names(s)[ind] ]]
class       : SpatRaster 
dimensions  : 10, 10, 2  (nrow, ncol, nlyr)
resolution  : 1, 1  (x, y)
extent      : 0, 10, 0, 10  (xmin, xmax, ymin, ymax)
coord. ref. :  
source(s)   : memory
names       :   A,   C 
min values  :   1,   2 
max values  : 100, 200 

Leave a ReplyCancel reply