I want to crop a raster and then save each peace into a list (or another way) with the pieces of the raster.
The idea:
- To preserve the covered area as equal for all of the pieces.
- To be possible for the user to set a percentage of extent area to be cropped. I.e. 10, 20, 30% of the all-area should be the extent of the grid.
A piece of reproducible code can be seen below: It has been developed by Chris and Robert Hijmans at this question here.
library(terra)
r <- rast(volcano)
n <- 10
Get the starting cells of interest
rows <- seq(1, nrow(r), by=n)
cols <- seq(1, ncol(r), by=n)
cells <- cellFromRowColCombine(r, rows, cols)
Get the coordinates
upper-left coordinates of the starting cells
xy <- xyFromCell(r, cells)
rs <- res(r)
xy[,1] <- xy[,1] - rs[1]/2
xy[,2] <- xy[,2] + rs[2]/2
add the lower-right coordinates of the end cell
xy <- cbind(xy[,1], xy[,1] + n*rs[1], xy[,2] - n*rs[2], xy[,2])
And loop
x <- lapply(1:nrow(xy), function(i) {
crop(r, xy[i,])
})
Verify
e <- lapply(x, \(i) ext(i) |> as.polygons()) |> vect()
plot(r)
lines(e, col="blue", lwd=2)
Note the right side of the cropped raster. It seems bad to perform statistics on these polygons.
Also: I would like to:
- the n on the beginning meaning a percentage of the area to be cropped in little rasters
- The user would enter 10, 20, or 30 as a number, for instance, meaning a percentage on the command to decide the size of the "window" to be cropped
- To preserve an equal space on the window, and to do that the command should vary a little between 10 and 20, for instance, to preserve the symmetry.