0
votes

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)
1

1 Answers

1
votes

The way I ended up dealing with the data extraction was to first create a quantitative raster for each category of the categorical raster rcat (with values=NA for pixels under other categories and rquant values for pixels under the relevant category). Then, for each of these new rasters, I extracted their information per polygon using the velox package devtools::install_github('hunzikp/velox') - great for extracting dat from large datasets.

library(raster)
library(maptools)
data("wrld_simpl")
devtools::install_github('hunzikp/velox')
library(velox)

sptmp <- SpatialPolygons(wrld_simpl@polygons)
rquantX <- raster("rquant_forcategoryXonly.tif")
Lvx <- velox(rquantX)
Lvo <- Lvx$extract(sptmp, fun = function(x) sum(x, na.rm = TRUE))
Lvo2 <- cbind(Lvo[,1], wrld_simpl@data)