Gap filling temporal raster objects

对着背影说爱祢 提交于 2019-12-02 08:00:39

问题


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:


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)


来源:https://stackoverflow.com/questions/33352251/gap-filling-temporal-raster-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!