【发布时间】:2016-08-01 05:28:01
【问题描述】:
我在 R 中使用 for 循环从文件夹中读取 netCDF 文件并提取给定经度、纬度列表的值。它看起来像工作,除了一个问题。当循环根据日期返回值时,它会在 2 月 28 日之后创建 1 月 29 日到 31 日。像往常一样,我希望在 2 月 28 日或 29 日(闰年)之后的 3 月 1 日。这是我的 R 代码:
# given latitude, longitude list
sb1 <- data.frame(longitude=1:10,latitude =1:10)
# Extracting zonal or sub-basin average rainfall from netCDF file
sb1_r <- c()
date <- c()
rain_month <- c()
rain_year <- c()
for (year in 1998:1998){
for (month in 1:3){
for (day in seq_along(1:31)){
FileName <- paste('3B42_daily',year,sprintf("%02d",month),sprintf("%02d", day),'7.SUB.nc', sep='.')
if (!file.exists(FileName)){
next
} else {
File <- nc_open(FileName)
rain <- ncvar_get(File, 'r')
sb1_r[day] <- mean(apply(sb1,1,function(x)rain[x[1],x[2]]),na.rm = TRUE)
date[day] <- paste(year,sprintf("%02d", month),sprintf("%02d", day),sep='-')
rain_month <- data.frame(date,sb1_r)
nc_close(File)
}
}
rain_year <- rbind(rain_year,rain_month)
}
}
您可以在此链接中找到三个月的每日 netCDF 数据: https://drive.google.com/open?id=0B8rqKaYt0VEaMWVGc1gzdXI1U28
【问题讨论】:
-
您在 1 月、2 月和 3 月拥有
for (day in seq_along(1:31))。但是,二月只有28天。这可能是问题吗?如果是这样,您需要自定义循环。 -
@Gandalf 但我没有名称为 3B42_daily.1998.02.29.7.SUB 等的 NetCDF 文件。为了避免这种情况,我在我的代码中加入了“if (!file.exists(FileName)){”。
-
只是要指出,在使用例如常规纬度/经度网格,因为网格单元的大小不同。因此,每个单元格中的值需要按单元格面积加权。简单地使用 CDO 自动解决这个问题要好得多 - 见下文。
标签: r loops netcdf cdo-climate