I have a raster file where all pixels either are 0 (background) or 1 (see below, available at https://drive.google.com/file/d/1s2g8srXSTL6t-znF9nWbwK8f0C0K5FNk/view?usp=sharing).

I want R to find all regions of connected pixels and give them a unique ID. Then, I want to generate a shapefile via rasterToPolygons with one polygon for each region.
From what I can see, clump does the region grouping well. My code so far is:

test <- raster("C:/Users/.../sinks.tif")
regions <- clump(test)
regions_shp <- rasterToPolygons(regions, na.rm = T)

But that rasterToPolygons gives me a single polygon for every pixel and does not take into account the clump ID. What am I doing wrong?

enter image description here


You can use the dissolve argument, which dissolves all features with same value into polygon (or multi-polygon)


test <- raster("sinks.tif")
regions <- clump(test)
regions_shp <- rasterToPolygons(regions, na.rm = T, dissolve = T)


result of regions_shp:

class       : SpatialPolygonsDataFrame 
features    : 887 
extent      : -1010199, -978803.9, -92699.52, -39895.62  (xmin, xmax, ymin, ymax)
crs         : +proj=aea +lat_1=25 +lat_2=50 +lat_0=37 +lon_0=87 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0 
variables   : 1
names       : clumps 
min values  :      1 
max values  :    887 
| improve this answer | |
  • thanks a lot, I was looking for that! – Florian Mlehliv Jan 27 at 10:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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