as.Date with two-digit years

六月ゝ 毕业季﹏ 提交于 2019-11-29 16:20:21
x = format(as.Date("10.10.61", "%d.%m.%y"), "19%y-%m-%d")
x = as.Date(x)
x
class(x)

Note that a single sub will slice the string and prepend the year with 19 so it is not so onerous:

as.Date(sub("(..)$", "19\\1", date), "%d.%m.%Y")
## [1] "1961-10-10"

chron Alternately, the chron package defaults to a cutoff of 30 so it will use 1961 by default:

library(chron)
as.Date(dates(date, format = "d.m.y"))
## [1] "1961-10-10"

In chron the year expansion rule is defined by the "chron.year.expand" option which by default is set to the year.expand function and that function's default cut.off is 30. See this SO post for more info: Add correct century to dates with year provided as "Year without century", %y

If all your dates in 1900s, then you can use this solution:

library(magrittr)
your_date = '10.10.61'
as.Date(your_date,format="%d.%m.%y") %>% format("19%y%m%d") %>% as.Date("%Y%m%d")
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!