r - R 中字符串到日期转换的 "standard unambiguous date"格式是什么?

标签 r date date-formatting strptime as.date

请考虑以下事项

$ R --vanilla

> as.Date("01 Jan 2000")
Error in charToDate(x) :
    character string is not in a standard unambiguous format

但该日期显然采用标准的明确格式。为什么会出现错误消息?

更糟糕的是,显然在没有警告或错误的情况下接受了不明确的日期,然后读取不正确!

> as.Date("01/01/2000")
[1] "0001-01-20"

我在 [R] 标签中搜索并发现了包含此错误消息的其他 28 个问题。所有解决方案和解决方法都涉及指定格式,iiuc。这个问题的不同之处在于我问的是无论如何定义的标准明确格式在哪里,它们可以更改吗?每个人都收到这些消息还是只有我收到这些消息?也许与语言环境有关?

换句话说,有没有比需要指定格式更好的解决方案?

29 questions containing "[R] standard unambiguous format"

> sessionInfo()
R version 2.15.2 (2012-10-26)
Platform: x86_64-w64-mingw32/x64 (64-bit)

locale:
[1] LC_COLLATE=English_United Kingdom.1252
[2] LC_CTYPE=English_United Kingdom.1252
[3] LC_MONETARY=English_United Kingdom.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United Kingdom.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

最佳答案

这是有记录的行为。来自 ?as.Date:

format: A character string. If not specified, it will try '"%Y-%m-%d"' then '"%Y/%m/%d"' on the first non-'NA' element, and give an error if neither works.

as.Date("01 Jan 2000") 会产生错误,因为格式不是上面列出的两种格式之一。 as.Date("01/01/2000") 产生错误答案,因为日期不是上面列出的两种格式之一。

我将“标准明确”表示为“ISO-8601”(尽管 as.Date 并不那么严格,因为“%m/%d/%Y”不是 ISO -8601)。

如果您收到此错误,解决方案是使用 ?strptime 中的详细信息部分中描述的格式指定日期(或日期时间)的格式.

确保转换规范的顺序以及任何分隔符与您的输入字符串的格式完全对应。另外,如果您的数据包含日/月名称和/或缩写,请务必特别小心,因为转换将取决于您的区域设置(请参阅 ?strptime 中的示例并阅读 ?LC_TIME ;另见strptime, as.POSIXct and as.Date return unexpected NA)。

关于r - R 中字符串到日期转换的 "standard unambiguous date"格式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14755425/

相关文章:

c# - 无法解析 DateTime

mysql - 使用日期的 MySQL 函数中的语法错误(也许是 DATEDIFF?)

从 API 返回的 JSON 日期格式(没有时间)

ruby-on-rails - 如何在 Rails 中将日期格式化为 JSON?

function - 在R中: How can I know if my packages are up to date?

sql - 如何快速将数据从R导出到SQL Server

r - 有没有办法生成类似于 mutate_at 或 mutate_if 的 Gather_at 或 Gather_if 函数

r - 如何从 R 中的复杂字符串中提取多个新列(str_sub 似乎没有做到这一点)

mysql 将两个日期字段与两个日期字符串进行比较

c# - 使用标准或自定义日期格式