2017-06-02 198 views
3

我有一個data.framelat S和lng s表示定義的矩形框的界限,像這樣多邊形

geohash north_lat south_lat east_lng west_lng 
1 gbsuv 48.69141 48.64746 -4.306641 -4.350586 
2 gbsuy 48.69141 48.64746 -4.262695 -4.306641 

什麼是這個轉換爲持有列的sf對象的最簡單方法POLYGON s?

回答

4

創建多邊形的關鍵是座標必須按順序形成一個封閉區域(即最後一個點與第一個點相同)。

因此,您的數據需要一些操作來創建座標,並將它們按順序排列。在我的例子,我有lapply

那麼剩下可以從sf examples

lst <- lapply(1:nrow(df), function(x){ 
    ## create a matrix of coordinates that also 'close' the polygon 
    res <- matrix(c(df[x, 'north_lat'], df[x, 'west_lng'], 
      df[x, 'north_lat'], df[x, 'east_lng'], 
      df[x, 'south_lat'], df[x, 'east_lng'], 
      df[x, 'south_lat'], df[x, 'west_lng'], 
      df[x, 'north_lat'], df[x, 'west_lng']) ## need to close the polygon 
     , ncol =2, byrow = T 
) 
    ## create polygon objects 
    st_polygon(list(res)) 

}) 

## st_sfc : creates simple features collection 
## st_sf : creates simple feature object 
sfdf <- st_sf(geohash = df[, 'geohash'], st_sfc(lst)) 

sfdf 
# Simple feature collection with 2 features and 1 field 
# geometry type: POLYGON 
# dimension:  XY 
# bbox:   xmin: 48.64746 ymin: -4.350586 xmax: 48.69141 ymax: -4.262695 
# epsg (SRID): NA 
# proj4string: NA 
# geohash     st_sfc.lst. 
# 1 gbsuv POLYGON((48.69141 -4.350586... 
# 2 gbsuy POLYGON((48.69141 -4.306641... 

plot(sfdf) 

enter image description here

採取這樣做