Skip to content

Instantly share code, notes, and snippets.

@benfasoli
Last active November 1, 2023 11:28
Show Gist options
  • Save benfasoli/67e4f94bec8def76ca5c234c483e08eb to your computer and use it in GitHub Desktop.
Save benfasoli/67e4f94bec8def76ca5c234c483e08eb to your computer and use it in GitHub Desktop.
Methods for extracting coordinates from spatial objects (e.g. SpatialPolygonsDataFrame)
# Ben Fasoli
library(sp)
library(rgdal)
shape <- readOGR(dsn = 'data', layer = 'four_samples')
head(shape@polygons[[1]]@Polygons[[1]]@coords)
# [,1] [,2]
# [1,] -111.6227 40.75247
# [2,] -111.6227 40.75243
# [3,] -111.6226 40.75185
# [4,] -111.6224 40.75108
# [5,] -111.6224 40.75105
# [6,] -111.6221 40.75080
head(raster::geom(shape))
# object part cump hole x y
# [1,] 1 1 1 0 -111.6227 40.75247
# [2,] 1 1 1 0 -111.6227 40.75243
# [3,] 1 1 1 0 -111.6226 40.75185
# [4,] 1 1 1 0 -111.6224 40.75108
# [5,] 1 1 1 0 -111.6224 40.75105
# [6,] 1 1 1 0 -111.6221 40.75080
head(ggplot2::fortify(shape))
# long lat order hole piece id group
# 1 -111.6227 40.75247 1 FALSE 1 25 25.1
# 2 -111.6227 40.75243 2 FALSE 1 25 25.1
# 3 -111.6226 40.75185 3 FALSE 1 25 25.1
# 4 -111.6224 40.75108 4 FALSE 1 25 25.1
# 5 -111.6224 40.75105 5 FALSE 1 25 25.1
# 6 -111.6221 40.75080 6 FALSE 1 25 25.1
@Averysaurus
Copy link

This is rad, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment