0

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. – Jeffrey Evans Mar 5 '14 at 20:19
3

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)
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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