R_Extracting coordinates from SpatialPolygonsDataFrame

Use the coordinates() function from the sp package. It should give you the values in a list format.

You can also get the Polygon attribute from the shapefile.

mfile = readOGR(dsn=dsn,layer=layername)
polys = attr(mfile,'polygons')
npolys = length(polys)
for (i in 1:npolys){
  poly = polys[[i]]
  polys2 = attr(poly,'Polygons')
  npolys2 = length(polys2)
  for (j in 1:npolys2){
     #do stuff with these values
     coords = coordinates(polys2[[j]])
  }
}

Finally, I figured out that I didn't parse the output correctly. The correct way to do is bdryData@polygons[[2]]@Polygons[[1]]@coords. Mind the difference in command polygons(Polygons and polygons) and it took me ages to find out.


This took me a while to figure out too. The following function I wrote worked for me. sp.df should be SpatialPolygonsDataFrame.

extractCoords <- function(sp.df)
{
    results <- list()
    for(i in 1:length(sp.df@polygons[[1]]@Polygons))
    {
        results[[i]] <- sp.df@polygons[[1]]@Polygons[[i]]@coords
    }
    results <- Reduce(rbind, results)
    results
}

Tags:

R

Geospatial

Slot