本文介绍了将正确的世纪添加到日期中,年份提供为“没有世纪的年份",%y的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 %d%b%y 格式的生日文件.一些例如.

I have an file with birthdays in %d%b%y format. 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")

这就是结果

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

这些是生日,我看到 2054.从这个 page 我看到 00 到 68 之间的年份值被编码为 20 世纪.有没有办法切换这个,在我的情况下,我只想将 00 到 12 编码为 20.

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. Is there a way to toggle this, in my case I want only 00 to 12 to be coded as 20.

推荐答案

1) chron.chron 默认使用 30,因此这会将它们首先转换为 Date(因为 chron 无法读取这些类型的日期),重新格式化为具有两位数年份的字符,转换为 chron 可以理解的格式,最后返回到 Date.

1) chron. 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.

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

这给出了 30 的临界值,但我们可以使用 chron 的 chron.year.expand 选项得到 13 的临界值:

That gives a cutoff of 30 but we can get a cutoff of 13 using chron's chron.year.expand option:

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, ...)
     }
)

然后重复原来的转换.例如,假设我们已经运行了这个选项语句,我们将使用 xx 得到以下内容:

and then repeating the original conversion. For example assuming we had run this options statement already we would get the following with our 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) 仅限日期.这是一个不使用 chron 的替代方法.你可能想用 Sys.Date() 替换 "2012-12-31" 如果想法是否则未来的日期真的要设置在 100 年前:

2) Date only. Here is an alternative that does not use 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:

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

添加了仅日期解决方案.

added Date only solution.

这篇关于将正确的世纪添加到日期中,年份提供为“没有世纪的年份",%y的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 14:18