# average certain raster cells in R

If I have two rasters, let's say x1 and x2, that are the same dimensions, how can I take the average of the two but only where both have data to have a third raster x3 that is a composite of the first two? For example, if the cell in row one column one for x1 has no data but x2 does then I want my final raster to just have the x2 value. If both rasters have data in the cell from row one column 2 then I want the resulting raster to have an average in that cell. I am sure this can easily be done in a for loop or perhaps an apply function but I am unsure how to set it up.

This sorts itself out with the base function mean.

``````mean(c(20,10),na.rm=TRUE) # where both values occur
mean(c(20,NA),na.rm=TRUE) # where the first value occurs
mean(c(NA,10),na.rm=TRUE) # where the second value occurs
mean(c(NA,NA),na.rm=TRUE) # where both values are nodata
``````

If you think of raster functions in terms of vectorization then things become simpler to conceptualize when applying a function. Given the above example you can simply pass "mean" to the raster "overlay" function.

``````require(raster)
x1 <- raster(ncol=50, nrow=50)
x1[x1] <- runif(length(x1[x1]),1,100)
x2 <- raster(ncol=50, nrow=50)
x2[x2] <- runif(length(x2[x2]),1,100)
x2[sample(1:ncell(x2),20)] <- NA

xmean <- overlay(x1, x2, fun = mean)
``````
• I knew there would be an easy function for it. I didn't know about overlay. Thanks for pointing that out Commented Nov 18, 2014 at 21:11