Skip to content

Instantly share code, notes, and snippets.

@jcheng5
Created May 8, 2017 22:57
Show Gist options
  • Save jcheng5/63adf1ebb76b32dc014f2004ab8ba6bb to your computer and use it in GitHub Desktop.
Save jcheng5/63adf1ebb76b32dc014f2004ab8ba6bb to your computer and use it in GitHub Desktop.
Convert ggfortify to sf
library(dplyr)
convertToSF <- function(df, id = "id", group = "group") {
# Extract the non-polygon data.
data <- df %>%
group_by_(id) %>%
do(head(., 1)) %>%
.[,setdiff(names(.), c("long", "lat", "order", "hole", "piece", "group"))]
# Extract the shapes. I don't know if this does the right
# thing with holes--are holes even supported by ggfortify?
features <- state.map %>%
group_by_(id, group) %>%
do(shape = list(cbind(.$long, .$lat))) %>%
ungroup() %>%
group_by_(id) %>%
do(shapes = sf::st_multipolygon(.$shape)) %>%
.$shapes %>%
sf::st_sfc()
sf::st_sf(features, data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment