I am trying to extract data from a raster from a layer of random points.
The input data are the raster where I have to extract the values and a shapefile of polygons. With this shapefile, I get a random sampling of points that are inside the polygons. This is done with the SF package and I get a layer sfc_POINTS. Then, I try to extract the values of my raster with these points using the raster package.
I get this error: Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘extract’ for signature ‘"RasterLayer", "sfc_POINT"’
Here is the code:
# Clean environment
rm(list = ls())
#Import packages
library(sf)
library(raster)
#Import data
shp = st_read("PATH_TO_MY_SHP")
rst = raster("PATH_TO_MY_RASTER")
#Random sampling
Rdmsamp = st_sample(shp, 1000, "random")
Rdmsamp_values = raster::extract(rst, shp)
If someone can help me please. PS: Is it possible to integrate also a distance condition in the sample points setup (e.g. a distance to the edges of the polygons or a minimum distance between the points ?)
Thanks
First with terra (the replacement for raster):
library(terra)
fv <- system.file("ex/lux.shp", package="terra")
v <- vect(fv)
fr <- system.file("ex/elev.tif", package="terra")
r <- rast(fr)
pts <- spatSample(v, 100, "random")
e <- extract(r, pts)
Now with sampling in sf
library(sf)
shp <- st_as_sf(v)
rsamp = st_sample(shp, 100, "random")
rsp <- vect(rsamp)
vals <- extract(r, rsp)
Or use that sample with raster
library(raster)
rr <- raster(fr)
sfsamp <- st_as_sf(rsamp)
vv <- extract(rr, sfsamp)