I'm extracting values for some coordinates from rasters using raster package. I'm planning to use a buffer of 1km to do the extraction. But it seems impossible using extract function in terra pakcage.
Much appreciated if you can help me out.
I'm extracting values for some coordinates from rasters using raster package. I'm planning to use a buffer of 1km to do the extraction. But it seems impossible using extract function in terra pakcage.
Much appreciated if you can help me out.
Just convert the coordinates to points and then create a buffer around them Here a benchmarck with different packages:
library(terra)
library(raster)
library(exactextractr)
library(sf)
#create example raster
r <- raster(ncol=36, nrow=18, vals=1:(18*36))
# extract values with coordinates (converted to points)
#create some coordinates
xy <- cbind(-50, seq(-80, 80, by=20))
#convert to points
sp <- SpatialPoints(xy)
#create a buffer around the points
sp_buffer <-st_buffer(st_as_sf(sp),20)
#extract ----------------------------------------------------------------
#raster
raster::extract(r, sp_buffer)
#terra
terra::extract(r, sp_buffer)
#exactextract
exactextractr::exact_extract(r,sp_buffer)
library(microbenchmark)
microbenchmark(raster=raster::extract(r, sp_buffer),
terra=terra::extract(r, sp_buffer),
exactextract=exactextractr::exact_extract(r,sp_buffer)
)
Unit: milliseconds
expr min lq mean median uq max neval cld
raster 56.0899 59.19100 65.547358 60.64650 62.12665 300.6713 100 b
terra 56.3695 58.90810 65.549521 60.47245 62.22330 179.3679 100 b
exactextract 8.0596 8.53215 9.447963 8.71500 8.91085 81.8115 100 a
as you can see exact_extract
is the fastest function for extracting values from polygons (7 time faster)