Search code examples
rclassbufferraster

How to create inner buffer for a specific raster class in R?


I have a large raster with 3 values (1,2,3). I want to create a zone of 20 meters for areas with value 3, but I want the buffer to be not outside (around) the areas of value 3 but inside these areas.

I have tried to use

my_zones<-  buffer(my_raster, width=20)

but this creates a buffer of 20 m around and outside of all classes.

How can I transform this? my raster includes the entire Europe, so I would also like a relatively fast way to do the zones.

Can anyone help me?

EDIT1: I have also tried to creat a negative buffer like buffer(my_raster, width=-20) but width cannot be negative.

EDIT2: I am not sure how to create a sample raster, so I tried the following with the terra package

my_raster <- rast(xmin=1, xmax=3, ymin=1, ymax=3, res=1, val=sample(1:4, 100^2, replace=T))

Solution

  • There is a negative buffer for polygons, but not for rasters. However you can inverse the process yourself.

    Example data (you can always start with ?buffer for inspiration)

    library(terra)
    r <- rast(ncols=20, nrows=20, xmin=0, xmax=20, ymin=0, ymax=20, crs="local")
    r[, 1:10] <- 1
    

    A standard buffer

    b <- buffer(r, width=5) 
    plot(b)
    

    To get the negative buffer, first flip the cells that are NA, and then use buffer. The ! is to make the buffered area TRUE instead of FALSE

    x <- ifel(is.na(r), 1, NA)
    bb <- !buffer(x, width=5)