split raster spatially in R

76 Views Asked by At

I have a spatraster collection at 1-km resolution covering the entire globe. I want to split the spatraster into 6 (or any number) of equally sized spatraster

The below code splits the raster by layer but not spatially

library(terra)
s <- rast(system.file("ex/logo.tif", package="terra"))
s
class       : SpatRaster 
dimensions  : 77, 101, 3  (nrow, ncol, nlyr)
resolution  : 1, 1  (x, y)
extent      : 0, 101, 0, 77  (xmin, xmax, ymin, ymax)
coord. ref. : Cartesian (Meter) 
source      : logo.tif 
colors RGB  : 1, 2, 3 
names       : red, green, blue 
min values  :   0,     0,    0 
max values  : 255,   255,  255 

y <- terra::split(s, c(1,2,3))
y # 3 layers. But I want to split it spatially not by layer
1

There are 1 best solutions below

0
Robert Hijmans On BEST ANSWER

You can use terra::makeTiles (or write your own loop that calls terra::crop).

For example, to split s in 6 tiles, you could do

# find the number or rows and columns of a tile
rc <- ceiling(dim(s)[1:2] / c(2,3))
rc
#[1] 39 34

# make tiles 
x <- makeTiles(s, rc)

x
#[1] "tile_1.tif" "tile_2.tif" "tile_3.tif" "tile_4.tif" "tile_5.tif"
#[6] "tile_6.tif"

You can combine tiles with terra::vrt

v <- vrt(x)