Search code examples
rgisspatialr-rasterterra

classify `SpatRaster` map using attributes not values


I would like to classify a raster map (SpatRaster) based on the attribute table attached to it, not the cell values.

Here is a reprex from the help of the terra::activeCat() function:

set.seed(0)
r <- rast(nrows=10, ncols=10)
values(r) <- sample(3, ncell(r), replace=TRUE) + 10
d <- data.frame(id=11:13, cover=c("forest", "water", "urban"), letters=letters[1:3], value=10:12)
levels(r) <- d
cats(r)

# [[1]]
# id  cover letters value
# 11 forest       a    10
# 12  water       b    11
# 13  urban       c    12

I would like to change cells with urban class (cover == "urban") into NA.

# this does not work
activeCat(r) <- 2
classify(r, cbind("urban", NA))
# this works but using the cell value
classify(r, cbind(13, NA))

Thanks


Solution

  • You can use subst

    Example data

    library(terra)
    set.seed(0)
    r <- rast(nrows=10, ncols=10)
    values(r) <- sample(3, ncell(r), replace=TRUE) + 10
    d <- data.frame(id=11:13, cover=c("forest", "water", "urban"), letters=letters[1:3], value=10:12)
    levels(r) <- d
    

    Solution

    s <- subst(r, "urban", NA)
    

    Although it is a bit odd to set a label to NA. So I would do this instead

    ss <- subst(r, 13, NA, raw=TRUE)
    

    Or the equivalent with classify that you show.

    for more complex cases, you can remove the categories and then reset them later

    cts <- cats(r)
    levels(r) <- NULL
    # do something with r
    # 
    levels(r) = cts