Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
568 views
in Technique[技术] by (71.8m points)

r - polygons from coordinates

I've got a data.frame with lats and lngs that define the boundaries of rectangular boxes, like so

  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

What's the easiest way to convert this into an sf object that holds a column of POLYGONs?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The key to creating polygons is that the coordinates have to be in sequence to form a closed area (i.e., the last point is the same as the first point).

So your data will need a bit of manipulation to create the coordinates, and put them in order. In my example I've done this with an lapply

Then the rest can be taken from the 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...