1

I want to use R to loop through multiple polygons in one shapefile and obtain a zonal statistic (mean) for each polygon from a single raster. The polygons are buffered points of villages (about 84 buffers), and the raster the Hansen GFW data.

I've imported spatialEco and used zonal.stats to obtain some statistics and also extract, but I want to make sure that these are correct and there is no data loss due to the overlap, so creating an iteration of some variety will enable me to be sure that the statistics are representative of each polygon.

ex <- extract(hansen_forest,village_buffer,fun='mean',na.rm=TRUE,df=TRUE,weights=TRUE)

zs <- zonal.stats(village_buffer, hansen_forest, trace = TRUE, stat = MEAN)
hrbrnsn
  • 21
  • 3
  • [See here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) on making an R question that folks can help with. That includes a sample of data, all necessary code and packages, and a clear explanation of what you're trying to do and what hasn't worked. – camille Nov 12 '19 at 18:49

1 Answers1

0

Iterating over polygons in a shapefile isn't too hard! First, lets load in a shapefile which contains all polygons:

# Sample shp, with multiple polygons (218)
shp = readOGR('C:\\SHP\\ecoregions.shp')

As we can see this shapefile has 218 polygons (features)

class       : SpatialPolygonsDataFrame 
features    : 218 
extent      : -140.9994, -52.36458, 41.67354, 83.63315  (xmin, xmax, ymin, ymax)

To loop over every polygon, we can make a for loop:

for(i in 1:nrow(shp)) { 
polygon <- shp[i,] 
# Do zonal statistics here

}

This will go through every single polygon in the shapefile, Hopefully this helps!

Aliyan Haq
  • 302
  • 1
  • 7