首页 > 解决方案 > 如何在 R 中拟合时间序列移动平均线?

问题描述

我有一个与示例类似的栅格堆栈,周期为 62 天。我想拟合一个长度等于 62 天的时间序列移动平均线。我怎样才能在 R 中做到这一点?

library(greenbrown)
data("ndvimap")

#here I have an issue as I do not know how to set the length and run the window
#filt<-focal(ndvimap, fun=mean, na.rm=T)#it does not work

谁能帮我?

标签: rmeanraster

解决方案


我不明白你是想每 62 层还是每 62 天总结一次堆栈。但是,对于这两种情况,这是一个可能的解决方案:

library(greenbrown)
library(raster)
data("ndvimap")

#do the mean every 62 layers
step <- 62
nlayer <- nlayers(ndvimap)
sequence <-
  split(1:nlayer, rep(1:round(nlayer / step), c(
    rep(step, 5), nlayer - floor(nlayer / step) * step
  )))

res <- lapply(sequence,FUN = function(x){
  mean <- calc(ndvimap[[x]],mean)
})
res <- stack(res)

#do the mean every 2 layers (~62 days)
step <- 2
sequence <- split(1:nlayer,rep(1:(nlayer/step),each=step))

res <- lapply(sequence,FUN = function(x){
  mean <- calc(ndvimap[[x]],mean)
})
res <- stack(res)

推荐阅读