I'm trying to rasterize a SpatialPolygons object in a way that I get the number of polygons that overlap with each cell of the raster. My polygons have holes. The issue I have is that if two holes overlap it includes this overlap in the count.
I've created a toy example:
library(sp)
library(raster)
p1 <- rbind(c(-180,-20), c(-140,55), c(10, 0), c(-140,-60), c(-180,-20))
hole <- rbind(c(-150,-20), c(-100,-10), c(-110,20), c(-150,-20))
p1 <- list(p1, hole)
p2 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55), c(-10,0))
p3 <- rbind(c(-180,-20), c(-130,55), c(0,60), c(40,5), c(15,-45), c(-180,-20))
p3 <- list(p3, hole)
pols <- spPolygons(p1, p2, p3)
pols@polygons[[1]]@Polygons[[2]]@hole
pols@polygons[[3]]@Polygons[[2]]@hole
r1 <- raster(ncol=180, nrow=180)
r <- rasterize(pols, r1, fun="count")
plot(pols, col=rgb(1,0,0,0.5))
plot(r)
I think this might be what was causing the problem associated to question use R to rasterize shapefile with holes? , but there is no final solutions. In question rasterize ESRI shapefile with holes but FALSE hole slots the problem is that the holes are not properly formated, but that's not my case. If you look at the holes, they are both TRUE, see:
pols@polygons[[1]]@Polygons[[2]]@hole
pols@polygons[[3]]@Polygons[[2]]@hole
Any help would be appreciated!