简体   繁体   English

将正确的世纪添加到日期中,年份提供为“没有世纪的年份”,%y

[英]Add correct century to dates with year provided as "Year without century", %y

I have an file with birthdays in %d%b%y format.我有一个%d%b%y格式的生日文件。 Some eg.一些例如。

# "01DEC71" "01AUG54" "01APR81" "01MAY81" "01SEP83" "01FEB59"

I tried to reformat the date as我试图将日期重新格式化为

o108$fmtbirth <- format(as.Date(o108$birth, "%d%b%y"), "%Y/%m/%d")

and this is the result这就是结果

# "1971/12/01" "2054/08/01" "1981/04/01" "1981/05/01" "1983/09/01" "2059/02/01"

These are birthdays and I see 2054. From this page I see that year values between 00 and 68 are coded as 20 for century.这些是生日,我看到 2054。从这个页面我看到 00 到 68 之间的年份值被编码为 20 世纪。 Is there a way to toggle this, in my case I want only 00 to 12 to be coded as 20.有没有办法切换这个,在我的情况下,我只想将 00 到 12 编码为 20。

1) chron . 1) 时间 chron uses 30 by default so this will convert them converting first to Date (since chron can't read those sorts of dates) reformatting to character with two digit years into a format that chron can understand and finally back to Date. chron 默认使用 30,因此这会将它们首先转换为 Date(因为 chron 无法读取这些类型的日期),重新格式化为具有两位数年份的字符,转换为 chron 可以理解的格式,最后返回到日期。

library(chron)
xx <- c("01AUG11", "01AUG12", "01AUG13") # sample data
as.Date(chron(format(as.Date(xx, "%d%b%y"), "%m/%d/%y")))

That gives a cutoff of 30 but we can get a cutoff of 13 using chron's chron.year.expand option:这给出了 30 的截止值,但我们可以使用 chron 的chron.year.expand选项获得 13 的截止值:

library(chron)
options(chron.year.expand = 
     function (y, cut.off = 12, century = c(1900, 2000), ...) {
        chron:::year.expand(y, cut.off = cut.off, century = century, ...)
     }
)

and then repeating the original conversion.然后重复原来的转换。 For example assuming we had run this options statement already we would get the following with our xx :例如,假设我们已经运行了这个选项语句,我们将使用xx获得以下内容:

> as.Date(chron(format(as.Date(xx, "%d%b%y"), "%m/%d/%y")))
[1] "2011-08-01" "2012-08-01" "1913-08-01"

2) Date only . 2) 仅日期 Here is an alternative that does not use chron.这是一个不使用 chron 的替代方法。 You might want to replace "2012-12-31" with Sys.Date() if the idea is that otherwise future dates are really to be set 100 years back:如果想法是未来的日期真的要设置在 100 年前,您可能想用Sys.Date()替换"2012-12-31"

d <- as.Date(xx, "%d%b%y")
as.Date(ifelse(d > "2012-12-31", format(d, "19%y-%m-%d"), format(d)))

EDIT: added Date only solution.编辑:添加仅日期解决方案。

请参阅相关线程的响应:

format(as.Date("65-05-14", "%y-%m-%d"), "19%y-%m-%d")
o108$fmtbirth <- format(as.Date(o108$birth, "%d%b%y"), "%Y/%m/%d")

o108$fmtbirth <- as.Date(ifelse(o108$fmtbirth > Sys.Date(), 
                                format(o108$fmtbirth, "19%y-%m-%d"),
                                format(o108$fmtbirth)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM