Search code examples
rspatialterra

updating raster values with a vector or matrix of values based on polygon field in R terra


Here I have a method to update selected parts of a raster with a new value (from this question

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

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

But now I would like to update the raster with a vector of values, rather than one value:

len <- nrow(r[lux]) 
r[lux] <- 1:len
# Error: [`[`] value is too long

I am not certain how to interpret the error, but I think it means I am passing the wrong data type to r[lux]. Any advice?


Solution

  • The length of lux is four.

    length(lux)
    [1] 4
    

    So you can replace the cell values with four new values.

    r[lux] <- 11:14
    

    I understand that you want to replace all cells covered by lux with a different number. That cannot be done with this type of replacement.

    If your raster is not very large, you could achieve that with something like this

    library(terra)
    p <- vect(system.file("ex/lux.shp", package="terra"))
    r <- rast(p, res=0.01)
    values(r) <- 1
    lux <- p[p$NAME_1 == "Luxembourg",]
    
    x <- rasterize(lux, rast(r))
    d <- as.data.frame(x, cells=TRUE)
    x[d$cell] <- 1:nrow(d)
    
    rr <- cover(x, r)
    

    Or like this. The code looks very similar, but the result is different because the cells are here ordered by polygon.

    e <- extract(r, lux, cell=TRUE, ID=FALSE)
    x[e$cell] <- 1:nrow(e)