rterra

Filter raster layers based on multiple terms


The terra package supports a very convenient matching method for layer selection for multi-layer raster data:

# expression based (partial) matching of names with single brackets: s['^A']

However, this rule does not take effect for the time being when dealing with multiple conditions, as follows: I want to select all layers whose names start with 'A' and 'C':

library(terra)
data <- rast(nrow = 5, ncol =5, nlyr =6, vals = runif(5*5*6)) |> 
  `names<-`(c('A-1', 'A-2', 'B-1', 'B-2', 'C-1', 'C-2'))

data['^C'] #success

data[c('^A', '^C')]  
#> data[c('^A', '^C')]
#class       : SpatRaster 
#dimensions  : 5, 5, 2  (nrow, ncol, nlyr)
#resolution  : 72, 36  (x, y)
#extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#coord. ref. : lon/lat WGS 84 (CRS84) (OGC:CRS84) 
#source(s)   : memory
#names       :         A-1,        A-2 
#min values  : 0.003353635, 0.03063317 
#max values  : 0.926166175, 0.99872097 
#Warning message:
#In grep(i, names(x)) :
#  argument 'pattern' has length > 1 and only the first element will be used

Is there a way to implement this without using grep to write additional matching rules? It would be useful to simplify the code if multiple matches could be made in the same way as in the example.


Solution

  • You can do

    d <- data["^A|^C"]
    
    d
    #class       : SpatRaster 
    #dimensions  : 5, 5, 4  (nrow, ncol, nlyr)
    #resolution  : 72, 36  (x, y)
    #extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
    #coord. ref. : lon/lat WGS 84 (CRS84) (OGC:CRS84) 
    #source(s)   : memory
    #names       :        A-1,       A-2,         C-1,        C-2 
    #min values  : 0.08889804, 0.0016772, 0.000832798, 0.04425668 
    #max values  : 0.97299366, 0.9975146, 0.947968749, 0.99642639 
    

    That is, instead of a vector of conditions, concatenate them with the OR symbol.