There are 5 rasters: r0, r1,r2,r3,r4 with same extent, columns and rows. Random nodata cell disperse in each raster. Now I expect to fill nodata values of r0 with mean values of the other rasters in the same position(the cell of same row and column number). Of course, the mean values of cell exclude nodata values. I can not find function in raster package. Actually, the basic function I expect is like 'con' in arcmap.


To compute the mean of rasters ignoring NA values:


To replace NA values in raster r0 with values from the mean of rasters:

r0[is.na(r0)] = mean(r1,r2,r3,r4,na.rm=TRUE)[is.na(r0)]

There's a little overhead there since you are computing the mean over all the raster and throwing away everything you don't need to fill in the NAs in r0.

  • I'm sorry that I omited description of raster. If all of cells in one position of r1,r2,r3,r4 are nodata, using na.rm will cause the mean value is zero. Because The rasters are extracted by shp file, so that outside of shp is defined as nodata. I don't expect calculate these cell when applied function mean.@Spacedman – chaobin zhang Dec 7 '19 at 15:24
  • Create some simple rasters for examples. eg r1 = raster(matrix(1:12,3,4));r1[1,1]=NA. Repeat for the other rasters and then tell us what the expected output is. – Spacedman Dec 7 '19 at 15:29

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.