如何从 R 中的另一个 shapefile 获取包含多边形质心的 shapefile 的多边形?

How to get polygons of a shapefile containing centroids of polygons from another shapefile in R?

我在 R 中使用两个 shapefile,我正在尝试 select 其中一个的多边形包含另一个 shp 的质心。

我已经能够分别获取每个文件的质心(附图),但我找不到完成上述任务的方法。在这个例子中,假设我只想获得内部有蓝色质心(来自 shp2)的多边形 (shp1)。

example

谢谢!

您可以使用 rgeos 包中的 gCentroid()gContains()

library(raster) ## For data and functions used to make example SpatialPolygons objects
library(rgeos)  ## For topological operations on geometries

## Make a couple of example SpatialPolygons objects, p1 & p2
p1 <- shapefile(system.file("external/lux.shp", package="raster"))
r <- raster(extent(p1))
r[] <- 1:10
p2 <- rasterToPolygons(r, dissolve=TRUE)

## Find centroids of p2
cc <- gCentroid(p2, byid=TRUE)

## Select Polygons in p1 that contain at least one of centroids from p2
p3 <- p1[apply(gContains(p1, cc, byid=TRUE), 2, any),]

## Plot to check that that worked
ared <- adjustcolor("red", alpha=0.6)
plot(p1)
plot(p3, add=TRUE, col="wheat")
plot(p2, add=TRUE, border=ared)
points(cc, pch=16, col=ared)