Search code examples
rvectorraster

How to efficiently read part of raster data intersecting with vector data in R?


Given a large raster dataset (ras) (ideally Cloud optimized GeoTIFF) in projection A and a vector dataset (vec) in projection B covering a small part of ras. What is an efficient way to get the raster data intersecting with vec in R?

One way would be to read the data, reproject it, crop it, mask it.

ras <- terra::rast(rasterpath)
vec <- sf::st_read(vectorpath)

ras_reproject <- terra::project(ras, terra::crs(vec))
ras_crop <- terra::crop(ras_reproject , vec)

But reprojection takes forever and I do not want to load the entire raster dataset in Memory.

Is there package with a function like read_raster(rasterpath, extent=vec)?


Solution

  • I am not sure if this works out in all situations yet, but the {{ezwarp}} library and the underlying {{vapour}} library which builds on gdal kind of did what I wanted

    library(ezwarp)
    
    ras_crop <- ezwarp(
      x = rasterpath, y = rasterpath, res = 10, cutline = vec,
      crop_to_cutline = TRUE, engine = "vapour"
    )