[R-sig-Geo] Converting raster to polygons with just one polygon for cells with common value
Lyndon Estes
lestes at princeton.edu
Fri Feb 25 19:06:08 CET 2011
Dear List,
I am trying to figure out how I can convert raster to polygons after
the fashion of ArcGIS, i.e. where contiguous raster cells with common
values are grouped into a single polygon.
Here's where I am so far:
library(raster)
library(gstat)
data(meuse.grid)
coordinates(meuse.grid) = ~x+y
gridded(meuse.grid) = TRUE
m2 <- as(meuse.grid, "SpatialGridDataFrame")
m3 <- raster(m2, layer = "soil") # Convert soil classes to raster
m4 <- m3 == 2 # Select just class 2
# Convert to polygons
m4.shp <- rasterToPolygons(m4, fun = function(x) {x == 1})
plot(m4.shp) # Produces a polygon for each grid cell
# To produce a single polygon, I then have to use unionSpatialPolygons
m4.shp.m <- unionSpatialPolygons(m4.shp, ID = rep(1, times =
length(m4.shp)), avoidGEOS = F)
plot(as(m4.shp.m, "SpatialLines"), add = T, col = "red")
This solution is very slow for my application, where I am trying to
merge polygons created from 0.0833 degree grids for much of Africa.
Is there a better solution than this?
A side question: even though I have rgeos installed, I cannot
circumvent gpclib, and have to set gpclibPermit() to true. I was
under the impression that rgeos allowed one to avoid gpclib. Am I
missing something on this, or have I mistakenly loaded libraries,
etc.? I am working on a Mac OSX 10.5.
Thanks, Lyndon
More information about the R-sig-Geo
mailing list