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?

  • 3
    Do you want the global mean, moving window mean or mean of each pixel across your time series? Please be clear in your questions. Commented Mar 5, 2014 at 20:19

1 Answer 1


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
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)
  • I am having a similar issue. I have a raster list (made up of 671 raster objects) and I am hoping to create a loop through them all to calculate the sum of each of their pixels.
    – Larissa
    Commented Mar 24, 2020 at 18:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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