Please consider the following

$ R --vanilla

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

But that date clearly is in a standard unambiguous format. Why the error message?

Worse, an ambiguous date is apparently accepted without warning or error and then read incorrectly!

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

I've searched and found 28 other questions in the [R] tag containing this error message. All with solutions and workarounds involving specifying the format, iiuc. This question is different in that I'm asking where are the standard unambiguous formats defined anyway, and can they be changed? Does everyone get these messages or is it just me? Perhaps it is locale related?

In other words, is there a better solution than needing to specify the format?

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

推荐答案

This is documented behavior. From ?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") yields an error because the format isn't one of the two listed above. as.Date("01/01/2000") yields an incorrect answer because the date isn't in one of the two formats listed above.

I take "standard unambiguous" to mean "ISO-8601" (even though as.Date isn't that strict, as "%m/%d/%Y" isn't ISO-8601).

If you receive this error, the solution is to specify the format your date (or datetimes) are in, using the formats described in the Details section in ?strptime.

Make sure that the order of the conversion specification as well as any separators correspond exactly with the format of your input string. Also, be sure to use particular care if your data contain day/month names and/or abbreviations, as the conversion will depend on your locale (see the examples in ?strptime and read ?LC_TIME; see also strptime, as.POSIXct and as.Date return unexpected NA).

R相关问答推荐

提取R中值和列名的所有可能组合

在R中将特定列的值向右移动

在R中使用数据集名称

如何在R中合并两个基准点?

par函数中的缩写,比如mgp,mar,mai是如何被破译的?

如何根据嵌套元素的名称高效而优雅地确定它属于哪个列表?

在ggplot2中更改小提琴情节的顺序

在使用bslb和bootstrap5时,有没有办法更改特定dt行的 colored颜色 ?

R Read.table函数无法对制表符分隔的数据正常工作

TreeNode打印 twig 并为其上色

更新R中的数据表(使用data.table)

查找所有站点的最小值

如何在使用箭头R包(箭头::OPEN_DATASSET)和dplyr谓词时编写具有整齐计算的函数?

提高圣彼得堡模拟的速度

我将工作代码重构为一个函数--现在我想不出如何传递轴列参数

将摘要图添加到facet_WRAP gglot的末尾

在R中的数据框上使用Apply()函数时,如何保留非数字列?

无法将条件case_when()应用于使用!!创建的新变量Mutations

如何预测原始数据集并将值添加到原始数据集中

策略表单连接两个非常大的箭头数据集,而不会 destruct 内存使用