2017-02-28 57 views
1

我有一組多邊形,其中一些相交和/或觸摸(共同邊框)。我正在使用R的sf包對多邊形執行操作。到目前爲止,我的方法是使用sf::st_union(),它可以根據需要連接相鄰和相交的多邊形,但它也會將所有多邊形合併到一個MULTIPOLYGON幾何中。我想將每個多邊形分隔爲一個sf(data.frame)類,其中每個多邊形對象都顯示爲一個行,在data.frame如何在執行st_union()操作後將多面幾何體分離爲多個多邊形對象?

下面顯示一個示例。我首先創建一個示例數據集:

# Creating four example polygons, of which two (two squares) are neighbors: 

    p1 <- rbind(c(0,0), c(1,0), c(3,2), c(2,4), c(1,4), c(0,0)) 
    pol1 <-st_polygon(list(p1)) 
    p2 <- rbind(c(3,0), c(4,0), c(4,1), c(3,1), c(3,0)) 
    pol2 <-st_polygon(list(p2)) 
    p3 <- rbind(c(4,0), c(4,1), c(5,1), c(5,0),c(4,0)) 
    pol3 <-st_polygon(list(p3)) 
    p4 <- rbind(c(3,3), c(4,2), c(4,3), c(3,3)) 
    pol4 <-st_polygon(list(p4)) 

    d = data.frame(some_attribute = 1:4) 
    d$geometry = st_sfc(pol1,pol2,pol3,pol4) 
    df = st_as_sf(d) 

    class(df) 
    #[1] "sf"   "data.frame" 

    df 
    # Simple feature collection with 4 features and 1 field 
    # geometry type: POLYGON 
    # dimension:  XY 
    # bbox:   xmin: 0 ymin: 0 xmax: 5 ymax: 4 
    # epsg (SRID): NA 
    # proj4string: NA 
    # some_attribute      geometry 
    # 1    1 POLYGON((0 0, 1 0, 3 2, 2 4... 
    # 2    2 POLYGON((3 0, 4 0, 4 1, 3 1... 
    # 3    3 POLYGON((4 0, 4 1, 5 1, 5 0... 
    # 4    4 POLYGON((3 3, 4 2, 4 3, 3 3)) 

plot(df)給出:

plot(df)

我然後執行st_union()操作以相交或觸摸(兩個平方以上)所有多邊形的幾何形狀組合成一個:

df_union <- df %>% st_union() 
    df_union 
    # Geometry set for 1 feature 
    # geometry type: MULTIPOLYGON 
    # dimension:  XY 
    # bbox:   xmin: 0 ymin: 0 xmax: 5 ymax: 4 
    # epsg (SRID): NA 
    # proj4string: NA 
    # MULTIPOLYGON(((3 3, 4 3, 4 2, 3 3)), ((4 0, 3 0... 

plot(df_union)結果:

plot(df_union)

如圖所示的df_union上述結果是一個MULTIPOLYGON幾何只有一行。我想執行每個多邊形成幾何分離,如上面的圖中,但造成幾個多邊形對象的操作,這東西相當於:

# Simple feature collection with 4 features and 1 field 
    # geometry type: MULTIPOLYGON 
    # dimension:  XY 
    # bbox:   xmin: 0 ymin: 0 xmax: 5 ymax: 4 
    # epsg (SRID): NA 
    # proj4string: NA 
    # some_attribute      geometry 
    # 1    1 POLYGON((0 0, 1 0, 3 2, 2 4... 
    # 2    2 POLYGON((3 0, 4 0, 5 1, 5 0... 
    # 3    3 POLYGON((3 3, 4 2, 4 3, 3 3)) 

此使用sf包我該怎麼辦?

+0

你只想工會那些相互接觸的多邊形? –

+1

是,對於彼此接觸和/或相交的聯合多邊形,將每個新多邊形作爲「sf」「data.frame」類對象中的一行返回。 – trevi

+1

然後'st_cast'將'MULTIPOLYGON'改爲'POLYGON' –

回答

3

感謝Edzer提供的答案和給我們很棒的sf包!

正如Edzer提到執行st_castMULTIPOLYGON對象轉換成幾個POLYGON對象:

df_union_cast <- st_cast(df_union, "POLYGON") 
    df_union_cast 
    # Geometry set for 3 features 
    # geometry type: POLYGON 
    # dimension:  XY 
    # bbox:   xmin: 0 ymin: 0 xmax: 5 ymax: 4 
    # epsg (SRID): NA 
    # proj4string: NA 
    # POLYGON((3 3, 4 3, 4 2, 3 3)) 
    # POLYGON((4 0, 3 0, 3 1, 4 1, 5 1, 5 0, 4 0)) 
    # POLYGON((0 0, 1 4, 2 4, 3 2, 1 0, 0 0))