10

我正在对 .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 层的示例文件(以减小大小)。

我不完全知道如何提出代码,对不起,但它应该是这样的:

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

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

谢谢

4

2 回答 2

12

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

1 月份的指数列表需要有 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]]

于 2015-08-04T04:24:04.243 回答
1

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

我设法使用calc. 所以你也可以使用:

#sum the layers
datasum <- calc(data,fun=function(x) { by(x, indices, sum)})
于 2020-06-25T14:18:23.730 回答