I want to create two polygons.
Asked
Active
Viewed 2.5k times
1 Answers
39
Here is an example.
library(raster)
# example data
x <- raster(system.file("external/test.grd", package="raster"))
To get the rectangular extent
e <- extent(x)
# coerce to a SpatialPolygons object
p <- as(e, 'SpatialPolygons')
To get a polygon that surrounds cells that are not NA
# make all values the same. Either do
r <- x > -Inf
# or alternatively
# r <- reclassify(x, cbind(-Inf, Inf, 1))
convert to polygons (you need to have package 'rgeos' installed for this to work)
pp <- rasterToPolygons(r, dissolve=TRUE)
look at the results
plot(x)
plot(p, lwd=5, border='red', add=TRUE)
plot(pp, lwd=3, border='blue', add=TRUE)
Five years later: Nowadays I would use terra, which does this much faster.
library(terra)
z <- rast(system.file("external/test.grd", package="raster"))
pe <- as.polygons(ext(z))
pr <- as.polygons(z > -Inf)
plot(z)
plot(pe, lwd=5, border='red', add=TRUE)
plot(pr, lwd=3, border='blue', add=TRUE)
Robert Hijmans
- 10,683
- 25
- 35


r <- r > -Infpart. What is it exactly doing? And how different is it fromvalues(r)[!is.na(values(r))] <- 1(which sets all locations that are not NA in r to 1). – csheth Apr 02 '16 at 18:53r > -Infis basicR. Doc(1,NA,3,NA) > -Infto see how it works. I have added an alternative (reclassify). Your alternative works but it is not a good one for large objects. – Robert Hijmans Apr 02 '16 at 19:08rasterToPolygons()part, and thereupon I shall evaluate your answer. Thanks for the-Infbit its going to be very useful! – csheth Apr 02 '16 at 21:22aggregateas you would not see the difference anyway. – Robert Hijmans Apr 03 '16 at 03:59aggregate()on r, it has not processed (computer equipped with 16 GB RAM). Problem is I need to keep the boundary as native as I can, since a DEM needs to be extracted from the resultant polygon. If I further down-sample my raster I will loose that boundary. Any work around? – csheth Apr 05 '16 at 10:09