[R-sig-Geo] Extract coordinates from SpatialPolygonsDataFrame

hadley wickham h.wickham at gmail.com
Thu Mar 19 22:48:42 CET 2009


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:
> 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:
>> Hi there,
>>
>> Nestled deep within the "polygons" slot of my SpatialPolygonsDataFrame
>> object is a list of xy coordinates I would like to extract.  Using
>> coordinates() only produces a single xy pair associated with the polygon
>> (1st entry?  Centroid?) and I cannot for the life of me manage another way,
>> though I presume it is far from impossible.  Could someone please direct me
>> on this?
>>
>> Cheers
>> Tyler
>>
>>       [[alternative HTML version deleted]]
>>
>> _______________________________________________
>> R-sig-Geo mailing list
>> R-sig-Geo at stat.math.ethz.ch
>> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at stat.math.ethz.ch
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>



-- 
http://had.co.nz/



More information about the R-sig-Geo mailing list