据我所知,没有这种功能。我有一个方便的函数,使用 lubridate
实现,基本上与你的一样。
getNcTime <- function(nc) {
require(lubridate)
ncdims <- names(nc$dim)
timevar <- ncdims[which(ncdims %in% c("time", "Time", "datetime", "Datetime", "date", "Date"))[1]]
times <- ncvar_get(nc, timevar)
if (length(timevar)==0) stop("ERROR! Could not identify the correct time variable")
timeatt <- ncatt_get(nc, timevar)
timedef <- strsplit(timeatt$units, " ")[[1]]
timeunit <- timedef[1]
tz <- timedef[5]
timestart <- strsplit(timedef[4], ":")[[1]]
if (length(timestart) != 3 || timestart[1] > 24 || timestart[2] > 60 || timestart[3] > 60 || any(timestart < 0)) {
cat("Warning:", timestart, "not a valid start time. Assuming 00:00:00\n")
warning(paste("Warning:", timestart, "not a valid start time. Assuming 00:00:00\n"))
timedef[4] <- "00:00:00"
}
if (! tz %in% OlsonNames()) {
cat("Warning:", tz, "not a valid timezone. Assuming UTC\n")
warning(paste("Warning:", timestart, "not a valid start time. Assuming 00:00:00\n"))
tz <- "UTC"
}
timestart <- ymd_hms(paste(timedef[3], timedef[4]), tz=tz)
f <- switch(tolower(timeunit),
seconds=seconds, second=seconds, sec=seconds,
minutes=minutes, minute=minutes, min=minutes,
hours=hours, hour=hours, h=hours,
days=days, day=days, d=days,
months=months, month=months, m=months,
years=years, year=years, yr=years,
NA
)
suppressWarnings(if (is.na(f)) stop("Could not understand the time unit format"))
timestart + f(times)
}
编辑:大家还可以看看 ncdf4.helpers::nc.get.time.series
编辑2: 注意,新提出并目前正在开发中的神奇 stars
包将自动处理日期,请参见第一篇博客文章以获取示例。
编辑3: 另一种方法是直接使用 units
包,这也是 stars
所使用的。你可以像这样做:(仍无法正确处理日历,我不确定 units
是否可以)
getNcTime <- function(nc) {
require(units)
require(ncdf4)
options(warn=1)
if (is.character(nc)) nc <- nc_open(nc)
ncdims <- names(nc$dim)
timevar <- ncdims[which(ncdims %in% c("time", "Time", "datetime", "Datetime", "date", "Date"))]
if (length(timevar) > 1) {
warning(paste("Found more than one time var. Using the first:", timevar[1]))
timevar <- timevar[1]
}
if (length(timevar)!=1) stop("ERROR! Could not identify the correct time variable")
times <- ncvar_get(nc, timevar)
timeatt <- ncatt_get(nc, timevar)
timeunit <- timeatt$units
units(times) <- make_unit(timeunit)
as.POSIXct(time)
}
stars
包将自动处理日期,有关示例,请参见第一篇博客文章:http://r-spatial.org/r/2017/11/23/stars1.html。 - AF7units
包似乎可以优雅地处理日期。值得一试。 - AF7