R as.Date转换世纪错误 [英] R as.Date conversion century error

查看:65
本文介绍了R as.Date转换世纪错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的数据集中,一列包含许多雇员的出生日期,因此许多雇员的出生日期在1960年至1980年之间。我正尝试使用as.Date格式化它们,其中一些结果并不符合我的预期。

In my dataset a column contains Date of Births of many employees so many of them lies in the range 1960 to 1980. I am trying to format them using as.Date and in some of them the results are not per my expectation.

示例:

as.Date("7/1/61","%m/%d/%y")

我希望它返回 1961 -07-01,但返回 2061-07-01。

i want it to return "1961-07-01" but it returns "2061-07-01".

推荐答案

阅读:

?strptime  # where all the formatting details are available




%y

无世纪的年份(00–99)。在输入时,值00到68分别以20和69到99的19为前缀-这是2004和2008 POSIX标准指定的行为,但是他们也说'预计在将来的版本中,默认世纪是根据两位数字的年份会改变。

%y
Year without century (00–99). On input, values 00 to 68 are prefixed by 20 and 69 to 99 by 19 – that is the behavior specified by the 2004 and 2008 POSIX standards, but they do also say ‘it is expected that in a future version the default century inferred from a 2-digit year will change’.

因此,您需要使用正则表达式来回溯日期,并且最好在进行字符串转换之前进行发送至as.Date:

So you need a regex to backdate and it's probably better to do as a string conversion before sending to as.Date:

dvec <- c("7/1/61", "7/1/79")
as.Date(  sub("/(..$)", "/19\\1",dvec)  , "%m/%d/%Y")
 [1] "1961-07-01" "1979-07-01"

如果这已投入生产当员工的年龄开始超过本年度的最后两位数字时,它将成为等待发生的错误。

If this goes into production it will become an error waiting to happen when the age of your employees starts to creep above the last two digits of the current year.

这篇关于R as.Date转换世纪错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆