如何将月平均值应用于 3d 数组中的每日数据,并将其存储到 4d 数组中?

问题描述 投票:0回答:1

我拥有 2 年期间的每日地理空间数据。数据位于两个 nc 文件中,每个文件包含 365 天的数据。我想对数据进行计算,然后计算每个网格框中每年每 12 个月的月平均值。

lons <- 584
lats <- 712
MyValues_ym <- array(0., c(lons, lats, 2, 12))
MyCalculation <- array(0., c(lons, lats, ts))  ## set up data array to fit dailycalculations 
MyMonths = c('01','02','03','04','05','06','07','08','09','10','11','12')
ts <- dim(P)[[3]]  ## set MyCalculation array coordinates the same as precipitation coordinates
## Dimension of precipitation coordinates: [584L, 712L, 365L]
## calculate MeanMonthly  #calculated monthly q0 
## Loop over months
for (m in 1:12) {
  MyValues_ym[, , y - 1982, m] <- apply(MyCalculation, c(2), mean)
}

这给出了错误:

Error in `[<-`(`*tmp*`, , , y - 1982, m, value = c(NA_real_, NA_real_,  : 
  subscript out of bounds

任何帮助将不胜感激。

我尝试使用

rowMeans
,但这并没有计算数组时间维度的平均值。我不确定如何计算所需特定维度的平均值。

我用 RowMeans 尝试过:

    # Loop over months
    for (m in 1:12) {     
    my_months_yearly <- format(daterange, '%m') == MyMonths[m]    
    MyValues_ym[,,y-1982,m]=rowMeans(Q0d[,,my_months_yearly], na.rm = TRUE, dims = 2) 

编辑

我现在已经做了 MRE:

lons <- 10
lats <- 10


MyYearlyMonthlyData <- array(0., c(lons,lats,1,12)) ## set up array for monthly calculation 
MyCalculationYr1 <- array(runif(1:100), c(lons, lats, 365)) ## set up data array to fit dailycalculations 

## set up the date range and months for the loop
start = '1985-01-01'
end = '1985-12-31'
daterange = seq(as.Date(start), as.Date(end), "days")
MyMonths = c('01','02','03','04','05','06','07','08','09','10','11','12')
y=1985

## the loop to generate monthly values of each day of each month for the year

for (m in 1:12) { 
  blMM <- format(daterange,'%m') == MyMonths[m]
  MyYearlyMonthlyData[,,y-1984,m] = rowMeans(MyCalculationYr1[,,blMM],na.rm=TRUE,dims=2) 
}  

r geospatial netcdf ncdf4
1个回答
0
投票

降水数据来自 TAMSAT 档案(根据您帖子下的评论)。我很快下载了一个文件,它符合 CF 元数据约定,这对于通过 NetCDF 文件分发的气象数据很常见。您可以通过检查“Conventions”全局属性来轻松检查:

nc <- nc_open("./rfe_file.nc")
ncatt_get(nc, "")$Conventions

这些文件通常包含 3 维数据数组,就像这里的情况一样。尺寸为

lon
lat
time
。您可以使用
CFtime 包
轻松处理 time 维度:

library(CFtime)

# Create a CFtime instance from the "time" dimension in your file
cf <- CFtime(nc$dim$time$units, nc$dim$time$calendar, nc$dime$time$vals)

# Create a factor over the months in your data file
mon <- CFfactor(cf, "month")

# Extract the data from the file
data <- ncvar_get(nc, "ref_filled")

# Aggregate to monthly mean (mm/day)
pr <- apply(data, 1:2, tapply, mon, mean)

# Re-arrange the dimension after tapply() mixed them up
pr <- aperm(pr, c(2, 3, 1))

# Label the dimensions
dimnames(pr) <- list(nc$dim$lon$vals, nc$dim$lat$vals, levels(mon))
nc_close(nc)

请注意,您现在将拥有一个 3 维数组,其中第 3 维有 24 个元素,带有“2021-01”、“2021-02”...“2022-12”等标签。

apply()
函数在前两个维度上应用函数
tapply()
tapply()
使用因子
mean()
应用
mon
函数,因此在结果中每个网格单元格都有两年的月平均值.

© www.soinside.com 2019 - 2024. All rights reserved.