2016-02-24 90 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)