在 R 中选择和提取多边形内的点(shapefile)

Raj*_*Raj 2 r clip

我有两个形状文件;一个是点文件(世界的一些信息),另一个是 21 个国家/地区的形状文件。

我需要提取属于一个国家的点。我必须在 QGIS 或 ArcGIS 中重复此步骤 21 次。

有没有什么方法可以在 R 中做到这一点,如果是在批处理中,那就太好了,因为我也必须对其他 4 个数据集重复此操作。提前致谢

Hor*_*ear 5

因此,作为如何使用的示例,over()请考虑以下模拟数据。

library(raster)
library(sp)

#generate point distribution | with (x,y) coordinates
set.seed(42);pts <- SpatialPoints(data.frame(x = runif(30, 1, 5), y = runif(30, 1, 5)))

#create polygons
df<-data.frame(X = c(rep(1,5),rep(2,5),rep(3,5),rep(4,5),rep(5,5)),
               Y = c(rep(seq(1,5,1),5)))
df$cell<-1:nrow(df) #polygon identifier (for later)

#make into spatial object (probably better way to do this)
coordinates(df) <- ~X+Y 
rast <- raster(extent(df), ncol = 5, nrow = 5)
grid<-rasterize(df, rast, df$cell, FUN = max)
grid<-rasterToPolygons(grid) #create polygons

#plot to check
plot(grid); points(pts)

#and extract
pointsinpolygon = over(SpatialPolygons(grid@polygons), SpatialPoints(pts))
Run Code Online (Sandbox Code Playgroud)

最后一点你也可以这样做

df$pointsinpolygon <- over(SpatialPolygons(grid@polygons), SpatialPoints(pts))

将结果直接写入数据帧。