I am trying to create a new raster layer that is made up of the mean values from 7 other raster layers. I get results using overlay function mean:

mean <- overlay(2000, 2001, 2002, 2003, 2004, 2005, fun=mean)

The results I get however are skewed by a large amount 0 values in many of the cells. As the data within the rasters changes each year some cells could have 0 values one year and a value of 56 the following, for example any particular cell may contain the following:

|    Year  |  Value  |
| 2000     | 0       |
| 2001     | 54      |
| 2002     | 78      |
| 2003     | 102     |
| 2004     | 0       |
| 2005     | 0       |

So while the mean is:39, I am trying to achieve the mean ignoring the 0 values so the result should be: 78.

I have tried changing the 0 values to NA:

2000[2000 == 0]<-NA
2001[2001 == 0]<-NA
2002[2002 == 0]<-NA
2003[2003 == 0]<-NA
2004[2004 == 0]<-NA
2005[2005 == 0]<-NA

Which works fine, however the bit that I can't get to work is the calculating of the mean as before but with ignoring these NA values. I have tried

mean <- overlay(2000, 2001, 2002, 2003, 2004, 2005, fun=mean,  na.rm=TRUE)

but the results this returns are incorrect. So I am just looking for a way to find the mean whilst ignoring zero values or NA values.

  • What package provides an overlay method for numeric?
    – mdsumner
    Jun 25, 2015 at 20:21
  • Well you must not be using this code I guess. Can you provide useable code? Don't use "mean" as a variable name either, it's already a function.
    – mdsumner
    Jun 25, 2015 at 20:25

2 Answers 2


I wanted to point out that you can rewrite the mean function, mean, which you can write yourself to do anything you want, including ditch the 0 values and calculate the mean. For example, if you want to ignore 0s:

meanIgnoringZeroes <- function(x) {

Then you can pass the function, meanIgnoringZeroes to overlay:

mean <- overlay(r2000, r2001, r2002, r2003, r2004, r2005, fun=meanIgnoringZeroes)

You can make the function anonymous as well:

mean <- overlay(r2000, r2001, r2002, r2003, r2004, r2005, fun=function(x){ mean(x[x!=0],na.rm=T)})

You cannot have R objects called "2000", so presumably these are fake names? Your example actually should work, so you may want to double check why you think that the results are incorrect.

@aaryno's approach should work. I would do this:

s <- stack(r2000, r2001, r2002, r2003, r2004, r2005)
x <- reclassify(s, cbind(0, NA))
r <- mean(x, na.rm=TRUE)
  • thanks for pointing out the variable name issue. I like this answer for reclassify
    – aaryno
    Jun 25, 2015 at 22:33

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.