R 中 rasterStack 的层数求和

Sum nlayers of a rasterStack in R

我正在处理以 .nc 文件组织的气候数据的日常观察。 我使用 raster 包的 stack 命令读取它们。每个文件(对应一年)是一个具有以下特征的RasterStack元素:

class       : RasterStack 
dimensions  : 360, 720, 259200, 365  (nrow, ncol, ncell, nlayers)
resolution  : 0.5, 0.5  (x, y)
extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax) 

每一层都是一天的值的栅格。
我想对图层求和以计算月度值。我认为解决方案应该使用 calc 或 stackApply {raster},但我找不到从 x 层到 y 层求和的方法,也找不到在求和之前对 RasterStack 进行子集化的方法。

我准备了一个只有12层的example file(为了减小体积)

我不太清楚如何提出代码,抱歉,但它应该是这样的:

library(raster)
setwd("myfolder")
data<-stack(mydata.nc)

datasum<- stackApply(data, ??? ,fun=sum)

谢谢

您可以使用 stackApply 来执行此操作。使用您的示例数据,看起来每个栅格图层的名称都是日期。您可以使用它来构建需要传递给 stackApply.

的索引

索引列表需要有 31 个 1 以表示一月份等。

你可以这样做:

    #get the date from the names of the layers and extract the month
    indices <- format(as.Date(names(data), format = "X%Y.%m.%d"), format = "%m")
    indices <- as.numeric(indices)

    #sum the layers
    datasum<- stackApply(data, indices, fun = sum)

结果将是一个 12 层的栅格堆栈。

要从堆栈中提取栅格图层的子集,您可以data[[c(1,2]]

我遇到了同样的问题,要计算长时间序列 .nc 文件的平均值,但是 stackApply 对我不起作用。

我设法使用 calc 解决了问题。所以你也可以使用:

#sum the layers
datasum <- calc(data,fun=function(x) { by(x, indices, sum)})