Search code examples
rraster

Fill the gaps in raster stack using subsequent layers


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.


Solution

  • MikeJewski's solution might work, but the cover function is designed for this and more direct. It is not clear how you want to use the next two layers. The mean:

    for(i in 1:(nlayers(s) - 2) ){
        s[[i]] <- cover( s[[i]], mean( s[[(i+1):(i+2)]], na.rm=TRUE))
    }
    

    Or first the closest (as MikeJewski assumed):

    for(i in 1:(nlayers(s) - 2) ){
        s[[i]] <- cover( s[[i]], s[[(i+1)]])
        s[[i]] <- cover( s[[i]], s[[(i+2)]])
    }
    

    This would be another, but probably inefficient, approach:

    f <- function(x) {
        for(i in 1:((ncol(x)-2)) ){
            x[is.na(x[,i]),i]  <- x[is.na(x[,i]),i+1]  
            x[is.na(x[,i]),i]  <- x[is.na(x[,i]),i+2]  
        }
        x
    }
    
    ss <- calc(s, f)