# Calculate raster mean within polygon limit using R

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(MeanMap)
``````

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`