0

I have found similar questions, but most use different packages.

I have a shapefile with 20 multipolygons, with a few attributes. All I want is to create a raster whereby each raster cell's value is the count of the polygons that overlap with that cell.

library(sf)
library(raster)
shapefile <- st_read("x.shp")

# Create a raster template with the desired resolution (e.g., 5 square kilometers)
res <- 5000  
raster_template <- raster(ext = extent(shapefile), res = res)

# Convert the shapefile to the same CRS as the raster template
shapefile <- st_transform(shapefile, crs(raster_template))

# Create a raster with the number of overlapping polygons in each cell
overlap <- rasterize(shapefile, raster_template, field = 1, fun = "count")

Alternatively, because 'field 1' is the Object ID, I've created an attribute that is consistently '1' for each feature. This is now field 5. So I've edited the code :

richness <- rasterize(shapefile, raster_template, field = 5, sum = "TRUE")

or

richness <- rasterize(shapefile, raster_template, field = 5, fun = sum)

However, all attempts return an empty raster. Some additional info on the objects: enter image description here

0

Your Answer

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

Browse other questions tagged or ask your own question.