Search code examples
rgisrasterterra

R - update raster values which fall inside a polygon


I'm working with environmental layers in R using terra. I want to modify the values of a raster that fall inside a polygon. I know the classify function that can update all the values of a raster, but I don't know how to apply this only to the area of the polygon. I also found a nice and neat way to change all values inside a polygon, like this:

myraster[mypolygon] <- 7

but I just need to update one particular value, not all, for example, change all cells containg the value 21 for the value 7.

I unsuccessfully tried:

myraster[mypoligon][myraster[mypoligon] == 21] <- 7

getting the message:

Error: [`[`] value is too long

As an alternative I'm thinking of getting the raster that intersects the polygon, then classify the values, and merge back this small raster with the original, but I wonder if a quicker process exists.

PS. I posted a reproducible example below as an answer.


Solution

  • Here is one way to get there using cover.

    Example data

    library(terra)
    p <- vect(system.file("ex/lux.shp", package="terra"))[3,]
    r <- rast(system.file("ex/elev.tif", package="terra"))
    

    Let's update the area of r that is covered by p to 400, but only if that area has values > 400.

    x <- mask(r, p)
    y <- clamp(x, -Inf, 400)
    z <- cover(y, r)
    

    If you wanted to change a particular value, let's say 482, to 1000 you could do

    yy <- classify(x, cbind(482, 1000))
    zz <- cover(yy, r)
    

    And a range of values

    yyy <- classify(x, cbind(480, 500, 1000))
    zzz <- cover(yyy, r)