I have a rasterlayer MeanMap and I would like to do some calculations of the raster values contained within a determinate polygon fregs. How can I calculate the mean and the median of the raster for each polygon?

> fregs
class       : SpatialPolygonsDataFrame 
features    : 86 
extent      : -117724.8, -58876.6, -124776.9, -70413.58  (xmin, xmax, ymin, ymax)
crs         : +proj=utm +zone=29 +datum=WGS84 +units=m +no_defs 
variables   : 6
names       : DICOFRE,           Freguesia,           Municipio, Distrito,          Des_Simpli, pop_res_ce 
min values  :  110501,       Ãguas Livres,           ALCOCHETE,   LISBOA,       Ãguas Livres,      11074 
max values  :  151007, Vila Franca de Xira, VILA FRANCA DE XIRA, SETÚBAL, Vila Franca de Xira,       9997 
> MeanMap
class      : RasterLayer 
dimensions : 500, 500, 250000  (nrow, ncol, ncell)
resolution : 175.4347, 145.9944  (x, y)
extent     : -118821.8, -31104.38, -139252.5, -66255.27  (xmin, xmax, ymin, ymax)
crs        : +proj=utm +zone=29 +datum=WGS84 +units=m +no_defs 
source     : memory
names      : layer 
values     : 1.967911, 34.79086  (min, max)
plot(fregs, add=T)

raster layer with limits overlayed


just found out the raster::extract() function, it does what i needed.

mean_freg = extract(MeanMap, fregs, method="simple", fun=mean, sp=T)

this line of code adds a column with the results I needed to the original SpatialPolygonsDataFrame fregs

  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Oct 16 '21 at 14:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.