简体   繁体   English

从栅格中提取值

[英]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.输入数据是我必须提取值的栅格和多边形的 shapefile。 With this shapefile, I get a random sampling of points that are inside the polygons.使用这个 shapefile,我可以对多边形内的点进行随机采样。 This is done with the SF package and I get a layer sfc_POINTS.这是通过 SF package 完成的,我得到了一层 sfc_POINTS。 Then, I try to extract the values of my raster with these points using the raster package.然后,我尝试使用光栅 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"'我收到此错误:(函数(类,fdef,mtable)中的错误:无法找到 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?) PS:是否可以在样本点设置中集成距离条件(例如到多边形边缘的距离或点之间的最小距离?)

Thanks谢谢

First with terra (the replacement for raster):首先是 terra (光栅的替代品):

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现在在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或将该样本与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.在提取我仅获得 NaN 值的值时,问题仍然存在。 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.这个问题只是来自用于每一层的 CRS,所以你必须考虑将不同的层重新投影到同一个 CRS。 Hopefully this clarification will help some people in the future.希望这个澄清将在未来帮助一些人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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