Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading