2016-02-24 48 views
2

我想要除去形状文件中的所有多边形,但要除去一个多边形。有没有办法做到这一点?溶解除形状文件中的所有多边形之外的其他所有多边形

这里是一个重复的例子:

library(rgeos) 
library(UScensus2000tract) 

# load data 
    data("oregon.tract") 

# plot map 
    plot(oregon.tract) 

enter image description here

# Dissolve all polygons 
    d <- gUnaryUnion(oregon.tract, id = [email protected]$state) 
    plot(d) 

enter image description here

在这个例子中,是否有可能解散由守道9501号的多边形?

回答

2

我认为这是你在找什么。如果要合并连续区域的连续成员,这会有所不同,但是您只需从多边形中移除第一个元素(整个状态),然后在其余区域上运行gUnaryUnion,然后重新添加邻接的成员到gUnaryUnion -ized状态的副本。

oregon = oregon.tract 
names(attributes(oregon.tract)) 
#[1] "bbox"  "proj4string" "polygons" "plotOrder" "data"  
#[6] "class" 
selected_tract_indices = which([email protected]$tract == 9501) 

oregon <- gUnaryUnion(oregon.tract, id = [email protected]$state) 
d = oregon 
npolygons = 1 
for (selected_tract_index in selected_tract_indices){ 
[email protected][[npolygons+1]] = [email protected][[selected_tract_index]] 

npolygons = npolygons + 1 
[email protected]=c([email protected],as.integer(npolygons)) 
} 

plot(d) 

Oregon with selected tract

该操作的输出是一个SpatialPolygon。如果您想将其转换回SpatialPolygonDataDrame,here是一种简单的方法:

# Extract polygon ID's 
(did <- sapply(slot(d, "polygons"), function(x) slot(x, "ID"))) 

# Create dataframe with correct rownames 
(d.df <- data.frame(ID=1:length(d), row.names = did))  

# Try coersion again and check class 
d <- SpatialPolygonsDataFrame(d, d.df) 
class(d)