[R-sig-Geo] obtain all vertices from SpatialPolygonsDataFrame

Michael Sumner mdsumner at gmail.com
Thu Feb 11 06:42:29 CET 2010

Hello, this example came up in discussion today - this will retrieve
all the raw coordinates from a SpatialPolygonsDataFrame.

I cannot find any helper functions for this in maptools or sp, but if
there are some I'd like to know. This doesn't do anything to tag each
vertex in terms of its origin in the hierarchy, and a helper function
for that might be nice to work out.

I thought it might be of interest. There was a similar discussion
here: https://stat.ethz.ch/pipermail/r-sig-geo/2009-March/005302.html

Regards, Mike

dsn <- system.file("vectors", package = "rgdal")[1]

p <- readOGR(dsn=dsn, layer="trin_inca_pl03")

## this shows  the number of coordinates in the first polygon
lapply(p at polygons[[1]]@Polygons, function(x) dim(x at coords))

## how many parts across each polygon?
unlist(lapply(p at polygons, function(x) length(x)))

## how many coordinates in the first part of each?
lapply(p at polygons, function(x) dim(x at Polygons[[1]]@coords))

## get them all, dropping the last as a duplicate
xy <- do.call("rbind", lapply(p at polygons, function(x1)
do.call("rbind", lapply(x1 at Polygons, function(x2)
x2 at coords[-nrow(x2 at coords), ]))))

plot(p, col = "grey")

points(xy, col = "red", pch = ".")

## exploration I used to figure out the lapply commands above

## 3 levels of hierarchy, because of possible multi-parts (holes and islands)
#[1] "data"        "polygons"    "plotOrder"   "bbox"   "proj4string"
slotNames(p at polygons[[1]])
#[1] "Polygons"  "plotOrder" "labpt"     "ID"        "area"
slotNames(p at polygons[[1]]@Polygons[[1]])
#[1] "labpt"   "area"    "hole"    "ringDir" "coords"

More information about the R-sig-Geo mailing list