[R-sig-Geo] Crop a SpatialPolygonsDataFrame by a bounding box/anotehr polygon
O'Hanlon, Simon J
simon.ohanlon at imperial.ac.uk
Thu Jun 21 12:28:44 CEST 2012
Dear all,
I would like to crop a particular contiguous area of country polygons to a rectangular bounding box, and return new polygons, from which I can work out the centroids. I would like to do this so that I can use the centroids of the cropped country polygons to work out nice label placements for a map. I am having trouble cropping a SpatialPolygonsDataFrame object by another polygon using gIntersection (I suspect this is not for this purpose?).
Can anyone help edit the following to make it work? The gIntersection command fails. I think I need to find an alternative, but I am not sure what to do yet. If anyone can suggest a command I'd be most grateful.
Many thanks in advance,
Simon
---
# Load relevant pacakges
library(ggplot2)
library(maptools)
library(rgeos)
library(plyr)
# Download and unzip the Natural Earth Country Polygon data
oldwd <- getwd()
tmp <- tempdir()
setwd(tmp)
url <- "http://www.naturalearthdata.com/http//www.naturalearthdata.com/download/50m/cultural/50m-admin-0-countries.zip"
dest <- paste(tmp,"\\tmp.zip",sep="")
download.file(url,dest) #File is 1.3Mb
unzip(dest)
# Read in the data to a SpatialPolygonsDataFrame
wld <- readShapePoly("ne_50m_admin_0_countries")
# Create bounding box polygon which we would like to use to crop polygons
bb <- readWKT("POLYGON((-18 4, 4 4, 4 18, -18 18, -18 4))")
proj4string(bb) <- proj4string(wld)
# Use gIntersection to crop the polygons to the borders of the bounding box - THIS FAILS
wa <- gIntersection(wld,bb)
# Work out the centroids of the new polygons (but we can't do that until we have the new polygons!)
wa.df <-as.data.frame(wa)
wld.lab <- data.frame(country = (wa.df$NAME), coordinates(wa))
# Cleanup
unlink(tmp,recursive=T)
setwd(oldwd)
More information about the R-sig-Geo
mailing list