convert a fortified data.frame back to sf object

試著忘記壹切 提交于 2019-12-10 19:17:27

问题


fiftystater package provides a great map of USA that has Hawaii and Alaska as insets below. The object fifty_states comes already fortified for use with ggplot2. However, I would like to plot this as an sf object using geom_sf.

As a more general question, what is the best way to convert a fortified data.frame back into sf polygon?

library(fiftystater)
fifty_states <– fifty_states

> head(fifty_states)
       long      lat order  hole piece      id     group
1 -85.07007 31.98070     1 FALSE     1 alabama Alabama.1
2 -85.11515 31.90742     2 FALSE     1 alabama Alabama.1
3 -85.13557 31.85488     3 FALSE     1 alabama Alabama.1
4 -85.13156 31.78381     4 FALSE     1 alabama Alabama.1
5 -85.13017 31.77885     5 FALSE     1 alabama Alabama.1
6 -85.11529 31.73157     6 FALSE     1 alabama Alabama.1

note this question polygons from coordinates is kind of similar but doesn't quite do what I need.


回答1:


this would work: you first convert to a point sf dataset using st_as_sf, and then create polygons from the points of each state/piece.

sf_fifty <- sf::st_as_sf(fifty_states, coords = c("long", "lat")) %>% 
  group_by(id, piece) %>% 
  summarize(do_union=FALSE) %>%
  st_cast("POLYGON") %>% 
  ungroup()

plot(sf_fifty["id"])

(see also https://github.com/r-spatial/sf/issues/321)



来源:https://stackoverflow.com/questions/49526198/convert-a-fortified-data-frame-back-to-sf-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!