Thursday, 3 March 2016

Mean by month on R stacked raster


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



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


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...