[GIS] Mean by month on R stacked raster

aggregationrrasterstack

I work with MODIS NDVI rasters in 2016. I have 23 rasters stacked in one object. I have 2 raster by month. I would like the average by months and conserve a raster for each month.

ndvi.stack <- stack(result)

# attribute name for each raster stacked
idx <- seq(as.Date('2016-01-17'), as.Date('2017-01-03'), '16 day')
names(ndvi.stack) <- idx

dim(ndvi.stack)
#[1] 302 268  23
## Set up color gradient with 100 values between 0.0 and 1.0
breaks <- seq(0, 1, by=0.01)
cols <- colorRampPalette(c("red", "yellow", "lightgreen"))(length(breaks)-1)

##plot
levelplot(ndvi.stack,at=breaks, col.regions=cols, main="NDVI 2016")

NDVI for each 16 days

I would like to get something like that
rasterViz package visualization

Best Answer

I have found on stack overflow a more generic way with the raster package using stackApply().

#get the date from the names of the layers and extract the month
indices <- format(as.Date(names(ndvi.stack), format = "X%Y.%m.%d"), format = "%m")
indices <- as.numeric(indices)

#sum layers
MonthNDVI<- stackApply(ndvi.stack, indices, fun = mean)
names(MonthNDVI) <- month.abb

## Set up color gradient with 100 values between 0.0 and 1.0
breaks <- seq(0, 1, by=0.01)
cols <- colorRampPalette(c("red", "yellow", "lightgreen"))(length(breaks)-1)
levelplot(MonthNDVI,at=breaks, col.regions=cols)

Et voilĂ  enter image description here