简体   繁体   中英

Extract values from raster

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 (eg 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)

I am here to answer my own question with the elements that I was given in the previous answer. The code used in the previous answer works well. A problem persisted on the extraction of the values for which I obtained only NaN values. This problem simply came from the CRS used for each layer, so you have to think about reprojecting your different layers to the same CRS. Hopefully this clarification will help some people in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM