Gap filling temporal raster objects

后端 未结 1 848
眼角桃花
眼角桃花 2021-01-23 19:55

Suppose I have 4 raster layers each belong to every other week of the month. I want to use linear interpolation to create new layers for each day. In this case, the first 2 rast

相关标签:
1条回答
  • 2021-01-23 20:30

    About the same question was asked two weeks ago. Here is the adapted answer for your example.

    library(raster)
    r1 <- raster(nrow=5, ncol=5)
    feb15 <- setValues(r1, runif(ncell(r1)))
    feb29 <- setValues(r1, runif(ncell(r1)))
    mar15 <- setValues(r1, runif(ncell(r1)))
    mar30 <- setValues(r1, runif(ncell(r1)))
    
    s <- stack(feb15, feb29, mar15, mar30)
    x <- calc(s, fun=function(y) approx(c(15,29,29+15,29+30), y, 1:59, rule=2)$y)
    names(x) <- c(paste('feb', 1:29), paste('march', 1:30))
    

    Unfortunately, approx fails when it only gets NA values. It "need at least two non-NA values to interpolate". Here is a work around:

    s[1:2] <- NA
    # fail <- calc(s, fun=function(y) approx(c(15,29,29+15,29+30), y, 1:59, rule=2)$y)
    
    f <- function(y) {
        if (sum(! is.na(y)) < 2) {
            return(rep(NA, 59))
        } else {
            approx(c(15,29,29+15,29+30), y, 1:59, rule=2)$y
        }
    }
    
    x <- calc(s, fun=f)
    
    0 讨论(0)
提交回复
热议问题