Gap filling temporal raster objects

2020-04-21 05:22发布

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 rasters belonging to the month of Feb with 29 days and the second 2 belong to March with 31 days. I want to know how to create daily raster objects that can fill the time period with the consideration of number of days in the month (29 rasters for Feb and 31 rasters for March). Thanks!

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)))

1条回答
Juvenile、少年°
2楼-- · 2020-04-21 06:16

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)
查看更多
登录 后发表回答