Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert a fortified data.frame back to sf object

Tags:

r

ggplot2

sf

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.

like image 397
sebdalgarno Avatar asked Mar 28 '18 04:03

sebdalgarno


People also ask

How do you convert SF to SP?

In order to convert an sf object to an sp object (which has a Spatial class) you can use the as() function with Class = "Spatial" . To convert back to sf you can use st_as_sf() and accept the defaults.

What is St_as_sf?

st_as_sf: Convert foreign object to an sf objectcharacter; name of the active list-column with simple feature geometries; in case there is more than one and sf_column_name is NULL , the first one is taken. fill.

What is an SF object in R?

At its most basic, an sf object is a collection of simple features that includes attributes and geometries in the form of a data frame. In other words, it is a data frame (or tibble) with rows of features, columns of attributes, and a special geometry column that contains the spatial aspects of the features.


1 Answers

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)

like image 169
lbusett Avatar answered Sep 23 '22 11:09

lbusett