【问题标题】:return NA when the date is not correct日期不正确时返回 NA
【发布时间】:2011-08-08 04:03:39
【问题描述】:
我正在尝试使用 R 命令 as.POSIXct 将字符串日期转换为 POSIXct
如果列表中的日期之一不正确(此处为 2 月 31 日),则返回错误。我怎样才能获得 NA?
我在帮助中看到 已知无效的日期时间将返回为 NA。 这是一个错误吗?
as.POSIXct(c("2011-02-02", "2011-02-31"), tz="GMT")
【问题讨论】:
标签:
r
datetime
formatting
posix
【解决方案1】:
您还应该向函数提供格式字符串,如下所示:
> as.POSIXct(c("2011-02-02", "2011-02-31"), tz="GMT", format='%Y-%m-%d')
[1] "2011-02-02 GMT" NA
问题是没有格式字符串,函数无法判断,字符串的哪一部分代表月份,哪一部分代表日期。
编辑:
这实际上是错误所抱怨的:
Error in as.POSIXlt.character(x, tz, ...) :
character string is not in a standard unambiguous format