Search code examples
rrasterterra

Why is the output of buffer in terra not working as a mask?


library(terra)

r <- rast(ncols=36, nrows=18)
r[500] <- 1
b <- buffer(r, width=5000000) 
plot(b)

s <- rast(ncols=36, nrows=18)
values(s) <- runif(ncell(s))

tst <- mask(s, b)


plot(tst)

Does anyone know why is tst here exactly the same as s? can I use the output of buffer as a mask?


Solution

  • What gets masked is configured by maskvalues and by default it's NA.
    So either change values outside of b buffer to NA or use mask(s, b, maskvalues = FALSE):

    library(terra)
    #> terra 1.7.39
    par(mfrow = c(2, 1))
    
    r <- rast(ncols=36, nrows=18)
    r[500] <- 1
    b <- buffer(r, width=5000000) 
    plot(b)
    
    s <- rast(ncols=36, nrows=18)
    values(s) <- runif(ncell(s))
    
    # set FALSE values to NA
    # b[!b] <- NA
    # or change maskvalues arg to match the mask raster:
    tst <- mask(s, b, maskvalues = FALSE)
    plot(tst)
    

    Created on 2023-08-03 with reprex v2.0.2