You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在metR>=0.14中读取时间单位为years的NetCDF文件并恢复正确年份

解决metR >=0.14版本读取"years since"格式NetCDF时间变量的问题

问题说明

部分NetCDF文件的时间变量单位采用years since {参考日期}格式(不符合Unidata规范),在metR 0.11.0中用ReadNetCDF()读取可直接得到正确年份;但升级到metR 0.14.0及以上版本后,执行:

nc_ts = ReadNetCDF("sample_yrtime.nc")

会触发如下警告:

In .parse_time(ncfile$dim[[dims[i]]]$vals, ncfile$dim[[dims[i]]]$units,: 
time unit has unrecognised units: years. Not parsing.

输出的data.table中time列仅为整数索引,无法直接获取对应年份。

解决方案

无需借助其他软件手动获取参考日期,可直接通过metR读取NetCDF元数据自动提取参考年份,步骤如下:

  1. 读取NetCDF元数据(不加载全量数据)
    通过ReadNetCDF()的out = "nc"参数仅读取文件元信息,避免加载大量数据:
library(metR)
library(data.table)

# 读取元数据
nc_meta <- ReadNetCDF("sample_yrtime.nc", var = NULL, out = "nc")
  1. 从时间单位字符串中提取参考年份
    利用正则表达式从时间单位字段中提取参考年份(兼容years since 1960或years since 1960-01-01等格式):
# 获取时间单位字符串
time_units <- nc_meta$dim$time$units

# 提取参考年份
yr0 <- as.integer(sub("years since ([0-9]+).*", "\\1", time_units))
  1. 读取数据并计算正确年份
    读取全量数据后,用整数索引加上参考年份得到真实年份:
nc_ts <- ReadNetCDF("sample_yrtime.nc")
nc_ts[, yr := time + yr0]

手动方法(原方案)

如果已经通过其他方式获取到参考年份,可直接沿用以下代码:

library(data.table)
yr0 = 1960
nc_ts[, yr := time + yr0]

内容的提问来源于stack exchange,提问作者climatestudent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 20:50:17