1

I want to convert a raster to multi-part polygons, using the raster value to determine which polygon each cell becomes a part of. I have provided an example of what I am looking to achieve below, where each cell of the raster is assigned to a single multi-part polygon. If I split the cell values into five intervals, I would want five multipart polygons.

Visual example of raster to 5 multipart polygons

I have attempted to use the "Raster to Polygon" tool in ArcMap, but was unsuccessful because no matter how I used to raster calculator to get rid of decimal points on the raster, decimals continued to remain. Is there a way to do this in R?

2

1 Answer 1

2

The following code first builds a sample data and uses function cut to make 5 classes, then converted to raster; converts to spatial and "dissolves" the polygons, merging together those neighboring polygons which have the same value:

library(raster)

s = sample(1:10,100, replace = T)  # build some sample data
ms = matrix(s, nrow =10)           # turn into a 10 x 10 matrix
rs = raster(ms)                    # the raster with numbers from 0 to 10

m = cut(s, 5, labels = F)       # we use cut to make the 5 classes
mx = matrix(m, nrow =10)        
r = raster(mx)                  # the raster with 5 classes

plot(rs, col =  grDevices::palette.colors(n = 6)[-1]) # 5 classes
raster::text(rs)                # plot the numbers

enter image description here

polys = raster::rasterToPolygons(r, dissolve = T)
print(polys)

class       : SpatialPolygonsDataFrame 
features    : 5 
extent      : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
crs         : NA 
variables   : 1
names       : layer 
min values  :     1 
max values  :     5
plot(polys, col = 2:6)
raster::text(rs)

enter image description here

# in R it is recommendable to use package `sf` for vector data
library(sf)
st_as_sf(polys)
2
  • 1
    Thank you for the effort you put into walking me through this. Because of memory limitations, I had to aggregate the raster before cutting and converting it to polygons, but your solution worked perfectly!
    – Kyle Allen
    Commented Nov 12, 2020 at 2:06
  • You may mark the answer as accepted if it solves your question
    – Elio Diaz
    Commented Nov 12, 2020 at 3:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.