2016-03-04 90 views

回答

2

你可以使用gCentroid()gContains()rgeos包:

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) 

enter image description here

+0

非常感謝!這工作在一個很好和優雅的方式。但現在我有另一個問題... 如果我想獲得包含另一個shape文件質心的每個shapefile的多邊形,我怎麼能做到這一點?類似於,同時獲得「x的質心在y中」和「y的質心在x中」。不知道我的解釋是否足夠好... 再次感謝! – JBSacristan

+0

不客氣。你的意思是像'ii < - apply(gContains(p1,cc,byid = TRUE),2,any)。 xx < - gCentroid(p1,byid = TRUE)[ii];點(xx,col =「blue」)'? –

+0

行動!對不起,我沒有回答。它以可視化的方式運行良好。再次感謝您的答案! – JBSacristan

相關問題