Images are better than words, so please take a look at 
I have
- RasterLayer object (filled with random values ​​here for illustrative purposes only, actual values ​​do not matter)
- SpatialPolygons object with lots and lots of polygons in it
You can recreate the example data that I used for the image with the following code:
library(sp) library(raster) library(rgeos)
For each raster cell, I want to know how many of them are covered by one or more polygons. Or actually: the area of ​​all polygons inside the raster cell, without what is outside the cell in question. If there are several polygons overlapping a cell, I need their common area.
The following code does what I want, but takes more than a week to work with the actual datasets:
I can squeeze out a bit more speed using sapply instead of for -loop, but the bottleneck seems to be somewhere else. The whole approach looks rather uncomfortable, and I wonder if I missed something obvious. At first I thought that rasterize() should be able to do this easily, but I cannot figure out what to add to the argument fun= . Any ideas?
source share