I wish, for each polygon of a SpatialPolygonsDataFrame polyA (in my case each country in the wrold from wrld_simpl or GADM), and for each category of a categorical raster rcat, sum the values of another raster with quantitative values rquant. The final output would be a dataframe with the following columns: country name, category name, summed value.
I am familiar with bits of code but these do not fully allow me to figure out the right script to write. Is someone able to help me? Apologies for not providing a reproducible example here. Note that I'm working with rasters with 0.0083 resolution (ncell = 933120000), so I don't think converting the rasters to dataframes is a good idea.
The following script sums values from rquant for each polygon
library(maptools)
data("wrld_simpl")
out <- extract(rquant, SpatialPolygons(wrld_simpl@polygons),na.rm=TRUE)
df <- data.frame(ISO3=wrld_simpl$ISO3, SUM=unlist(lapply(out, sum, na.rm=TRUE)))
The following script sums values from rquant for each category of rcat
zonalstats <- zonal(rquant, z=rcat, fun='sum', digits=0, na.rm=TRUE, count=T)