I would like to create a function to count the number of raster cells within the polygons of a SpatialPolygonsDataframe object and adding the value as a new column without using a loop. I cannot find how to do it...
Here is my code:
library(sp)
library(raster)
# Create a SpatialPolygonsDataframe and a raster objets to overlay
# Polygons
p1 <- rbind(c(-180,-20), c(-140,55), c(-50, 0), c(-140,-60), c(-180,-20))
p2 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55), c(-10,0))
p3 <- rbind(c(-125,0), c(0,60), c(40,5), c(15,-45), c(-125,0))
polys <- as(spPolygons(p1, p2, p3), "SpatialPolygonsDataFrame")
# Raster
p4 <- rbind(c(-180,10), c(0,90), c(40,90), c(145,-10),
c(-25, -15), c(-180,0), c(-180,10))
rpol <- spPolygons(p4)
r <- raster(ncol=90, nrow=45)
grd <- rasterize(rpol, r, fun=sum)
# Function to count the share of occupied cells per polygon
myFunction <- function(polys,grd){
over <- crop(mask(grd, polys), polys)
share <- length(over[!is.na(over)]) / ncell(over) * 100
return(share)
}
myFunction(polys,grd)
Thanks a lot for your help!