Search code examples
rspatialterra

updating raster values based on polygon field in R terra


I have a raster and vector with the same spatial extent. The raster has all values = 1.

What I want is to change the values in the raster based on which polygon they fall in.

library(terra)
## terra 1.7.19
f <- system.file("ex/lux.shp", package="terra")
p <- vect(f)
p

r <- rast()
ext(r) <- ext(p)
r
values(r) <- 1

values(r)[p$NAME_1 == "Luxembourg",] <- 2

I was really hoping this code would make the areas called "Luxembourg" as value = 2, but instead it didn't, which means I clearly have the wrong idea.

Maybe someone else has a much better idea.


Solution

  • Example data

    library(terra)
    p <- vect(system.file("ex/lux.shp", package="terra"))
    r <- rast(p, res=0.01)
    values(r) <- 1
    

    A classical approach

    lux <- p[p$NAME_1 == "Luxembourg",]
    x <- rasterize(lux, r, 2, update=TRUE)
    

    You could also do the last step with

    r[lux] <- 3
    

    So you were not far off. It works like this:

    r[p[p$NAME_1 == "Luxembourg",]] <- 4