[GIS] How to create a loop in R to average ndvi raster time series

loopndvir

I have monthly ndvi raster geotiffs for multiple years. I need to run a loop to get the average of each of these ndvi grids/rasters.

Each of my ndvi rasters contains 143 pixels. I would like the mean of all the pixels within a raster across my time series.

Can someone offer any advice?

Best Answer

You can use cellstats in the raster package to calculate a global mean for each of your raster layers. To illustrate:

# Create some sample data
r1 <- matrix(rnorm(400),20,20)
x = raster(r1)
r2 <- matrix(rnorm(1000),20,20)
y = raster(r2)

# Calculate global mean in the multi-layer object
cellStats(brick(x, y), mean)

The results:

> cellStats(brick(x, y), mean)
    layer.1     layer.2 
0.001735036 0.047742064 

The same thing, but this time in a for loop:

# Get a list of NDVI's
setwd("C:/temp_ndvi")
files = list.files(getwd(), pattern = "\\.tif$")  # Get only the .tif files

# Loop through files and print global mean for each raster
for (i in files) {
  j = cellStats(brick(i), mean)
  print(j)
}