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

nbnkbykc  于 2023-10-13  发布在  其他
关注(0)|答案(1)|浏览(120)

我有两年来的每日地理空间数据。数据在两个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) 
}
yyyllmsg

yyyllmsg1#

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

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

这些文件通常包含三维数据数组,就像这里的情况一样。尺寸为lonlattime。您可以使用CFtime package轻松处理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维的3d数组,该数组具有24个元素,标签为“2021-01”,“2021-02”...“2022-12”。apply()函数在前两个维度上应用函数tapply()tapply()应用使用因子monmean()函数,因此结果中每个网格单元具有两年的月平均值。

相关问题