1
votes

I wish to extract for each ISO3 (column name in the spatial polygon dataframe wrld_simpl), the sum of the pixel values of a raster r. I was thinking of using the function rasterize, followed by zonal, but when rasterising wrld_simpl, I lose the character strings defining the ISO3 (e.g. AUS, USA…). Thank you very much for your suggestion! Ideally, my final output will be a dataframe in which each ISO3 is associated with a value (corresponding pixels value sum)

library(raster)
library(maptools)
# wrld_simpl spatial polygon dataframe
data("wrld_simpl")
#sample raster r
r <- raster(ncol=4320, nrow=2160)
r[] <- 1:ncell(r)
#rasterise
wrld_simpl_rast <- rasterize(wrld_simpl,r, field=wrld_simpl@data[,3]) #problem: when I rasterise, the factors of ISO3 are converted into numbers (from 1 to 246)
1

1 Answers

1
votes

raster::extract() seems to be the useful function here:

library(raster)
library(maptools)
data("wrld_simpl")
r <- raster(ncol=4320, nrow=2160); r[] <- 1:ncell(r)

out <- extract(r, SpatialPolygons(wrld_simpl@polygons))
df <- data.frame(ISO3=wrld_simpl$ISO3, SUM=unlist(lapply(out, sum)))
head(df)
 ISO3         SUM
1  ATG    11309698
2  DZA 98754992979
3  AZE  3353129894
4  ALB  1051339774
5  ARM  1177578642
6  AGO 79826243906

See also the post https://gis.stackexchange.com/q/66795/118888.