Skip to content

Extract coordinates from SpatialPolygonsDataFrame

6 messages · T.D. Rudolph, Torleif Markussen Lunde, Agustin Lobo +1 more

#
Hi 

In your case I guess you only need part 1. If there are more than 1 polygon 
you would also need part 2. As far as i know there are no inbuilt functions 
to extract coordinates from a SpatialPolygon. 

##
#part 1
nc <- readShapePoly(system.file("shapes/sids.shp", package="maptools")[1], 
		    proj4string=CRS("+proj=longlat +datum=NAD27"))

lonlat <- lapply(slot(nc, "polygons"), function(x) lapply(slot(x,
   "Polygons"), function(y) slot(y, "coords")))

#part 2
for (i in 1:dim(summary(lonlat))[1]) {
  size <- length(unlist(lapply(lapply(lonlat[i], lapply, dim), unlist)))
  if (size == 2) { res2 <- data.frame(unlist(lonlat[i], recursive=FALSE))
    } else lonlat.tmp <- unlist(lonlat[i], recursive=FALSE)
  if (size != 1) lonlat2 <- do.call(rbind, lapply(lonlat.tmp, data.frame))
  res2$ID <- i
  if (i == 1) lonlat3 <- lonlat2 else lonlat3 <- rbind(lonlat3, lonlat2)
}

lonlat3
##

Maybe this could be more efficient (part 2), but at least it works.

Best wishes 
Torleif
On Thursday 19 March 2009 10:14:51 pm Tyler Dean Rudolph wrote:
#
a small correction.

in the loop;
replace  if (size != 1) lonlat2 ...
with
if (size != 2) lonlat2 ...

best
Torleif
On Thursday 19 March 2009 10:37:42 pm Torleif Markussen Lunde wrote:

  
    
#
I have the following code in ggplot2 for turning a SpatialPolygon into
a regular data frame of coordinates.  You'll need to load ggplot2, and
then run fortify(yoursp).

fortify.SpatialPolygonsDataFrame <- function(shape, region = NULL) {
  attr <- as.data.frame(shape)
  # If not specified, split into regions based on first variable in attributes
  if (is.null(region)) {
    region <- names(attr)[1]
    message("Using ", region, " to define regions.")
  }

  # Figure out how polygons should be split up into the region of interest
  polys <- split(as.numeric(row.names(attr)), attr[, region])
  cp <- polygons(shape)

  # Union together all polygons that make up a region
  try_require(c("gpclib", "maptools"))
  unioned <- unionSpatialPolygons(cp, invert(polys))

  coords <- fortify(unioned)
  coords$order <- 1:nrow(coords)
  coords
}

fortify.SpatialPolygons <- function(model, data, ...) {
  ldply(model at polygons, fortify)
}

fortify.Polygons <- function(model, data, ...) {
  subpolys <- model at Polygons
  pieces <- ldply(seq_along(subpolys), function(i) {
    df <- fortify(subpolys[[model at plotOrder[i]]])
    df$piece <- i
    df
  })

  within(pieces,{
    order <- 1:nrow(pieces)
    id <- model at ID
    piece <- factor(piece)
    group <- interaction(id, piece)
  })
}

fortify.Polygon <- function(model, data, ...) {
  df <- as.data.frame(model at coords)
  names(df) <- c("long", "lat")
  df$order <- 1:nrow(df)
  df$hole <- model at hole
  df
}

fortify.SpatialLinesDataFrame <- function(model, data, ...) {
  ldply(model at lines, fortify)
}

fortify.Lines <- function(model, data, ...) {
  lines <- model at Lines
  pieces <- ldply(seq_along(lines), function(i) {
    df <- fortify(lines[[i]])
    df$piece <- i
    df
  })

  within(pieces,{
    order <- 1:nrow(pieces)
    id <- model at ID
    piece <- factor(piece)
    group <- interaction(id, piece)
  })
}

fortify.Line <- function(model, data, ...) {
  df <- as.data.frame(model at coords)
  names(df) <- c("long", "lat")
  df$order <- 1:nrow(df)
  df
}


Hadley

On Thu, Mar 19, 2009 at 4:37 PM, Torleif Markussen Lunde
<torleif.lunde at cih.uib.no> wrote:

  
    
#
Hadley,

It would be great if you could put your code
in the wiki
http://wiki.r-project.org/rwiki/doku.php?id=tips:spatial-data

I think that David Hugh-Jones has contributed a lot to
this site and he might advice on the best way of doing it
(David: sorry if I'm wrong on this)

Agus
hadley wickham wrote:
.../...

-------------- next part --------------
A non-text attachment was scrubbed...
Name: alobolistas.vcf
Type: text/x-vcard
Size: 251 bytes
Desc: not available
URL: <https://stat.ethz.ch/pipermail/r-sig-geo/attachments/20090320/d293d21d/attachment.vcf>
#
I don't mind if the code is put on the wiki, but I don't want to keep
it up-to-date in to places, and people will be able to use it directly
from the next release of ggplot2.

Hadley