Suppose I have a raster stack that each layer has data gap in. I want to use the next two layers in the stack to fill the gaps of each layer:
library(raster)
r1 <- raster(ncol=20,nrow=20, xmn=0, xmx=20, ymn=0,ymx=20)
r1[] <- 1:20
r2 <- r3 <- r4 <- r5 <- r1
set.seed(0)
r1[sample(1:ncell(r1), size = 20)] <- NA
r2[sample(1:ncell(r2), size = 30)] <- NA
r3[sample(1:ncell(r3), size = 10)] <- NA
r4[sample(1:ncell(r4), size = 18)] <- NA
r5[sample(1:ncell(r5), size = 18)] <- NA
s <- stack(r1, r2, r3, r4, r5)
In this case r2 and r3 will be used to fill the gaps in r1 and so forth.