Search code examples
rgisrasterr-rasterterra

How to select a section of a raster in R using a search window?


I want to select a group of pixels from a raster.

  • The user should enter an n value for selecting the number of columns and rows (or window size).

  • A window would fetch the number of pixels defined.

  • Would return a raster with the values.

Below is a piece of reproducible example:

library(terra)
r <- terra::set.ext(rast(volcano), terra::ext(0, nrow(volcano), 0, ncol(volcano)))
plot(r)

The idea is to start from the upper/left size using, i.e., 10 pixels for rows and cols (100 pixels as total) as a box window search.

For this I thought to get the min and max extent (using terra package) as the code below:

w_10 <- c(xmin(terra::ext(r)),xmin(terra::ext(r))+10,ymin(terra::ext(r)),ymin(terra::ext(r))+10)

After I imagine some iterations, the window search will go through all the raster lengths and should return pieces of rasters.

After all, the objective is to get different groups of pieces raster sizes, as in the image below:

enter image description here


Solution

  • You can use standard indexing

    library(terra)
    f <- system.file("ex/elev.tif", package="terra")
    r <- rast(f)
    
    w10 <- r[1:10, 1:10, drop=FALSE]
    

    Or use crop

    xmin <- xmin(r)
    ymax <- ymax(r)
    rs <- res(r)
    
    n <- 10
    xmax <- xmin + n * rs[1] 
    ymin <- ymax - n * rs[2]
    
    x <- crop(r, c(xmin, xmax, ymin, ymax))