I have a raster with text values in cells, and I need to find cells where a certain word occurs. For a vector, I would use grepl, however applying it to the raster cell values returns all FALSE.
library(terra)
x <- rast(ncol = 10, nrow = 10)
x[] <- sample(c("AA", "AB", "BB"), size = 100, replace = TRUE)
a <- app(x, fun = \(i) grepl("A", i))
a
# class : SpatRaster
# dimensions : 10, 10, 1 (nrow, ncol, nlyr)
# resolution : 36, 18 (x, y)
# extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
# coord. ref. : lon/lat WGS 84
# source(s) : memory
# name : lyr.1
# min value : 0
# max value : 0
I could mimic the desired behaviour with:
A <- (x == "AA") + (x == "AB")
A <- A > 0
But my data do not allow full matches. How can I find raster cell values that contain a word in a character string?

SpatRasters with character cell values are categorical rasters: the raster itself stores an index into a list of categories (just like a factor works). That's why you can't apply a function likegrepl()directly on the raster values (theapp()function currently doesn't support that, apparently). You should work with the category labels and values instead.To demonstrate what I mean:
That's just the values stored in the raster, not the character labels that they represent. The categories are returned as a list with an element for each layer in the
SpatRaster, each being adata.frame:So what you want to do is in the first layer find the
values that correspond to thelabelmatching your search:And then apply those
hitsto your raster: