简体   繁体   English

字符2位数的年份转换为仅年份

[英]Character 2 digit year conversion to year only

Using R 使用R

Got large clinical health data set to play with, but dates are weird 有大量的临床健康数据可供使用,但日期很奇怪

Most problematic is 2digityear/halfyear , as in 98/2 , meaning at some point in 1998 after July 1 问题最多的是2digityear/halfyear ,如98/2 ,即1998 July 1 1998之后的某个时候

I have split the column up into 2 character columns, eg 98 and 2 but now need to convert the 2 digit year character string into an actual year. 我已将该列拆分为2个字符列,例如982但现在需要将2位数的年份字符串转换为实际年份。

I tried as.Date(data$variable,format="%Y") but not only did I get a conversion to 0098 as the year rather than 1998 , I also got todays month and year arbitrarily added (the actual data has no month or day). 我尝试了as.Date(data$variable,format="%Y")但不仅将年份转换为0098 ,还不如将其转换为1998 ,我还任意添加了今天的月份和年份(实际数据没有月份)或一天)。

as in 0098-06-11 0098-06-11

How do I get just 1998 instead? 我怎样才能得到1998年呢?

Not elegant. 不优雅。 But using combination of lubridate and as.Date you can get that. 但是使用lubridate和as.Date的组合可以达到目的。

library(lubridate)
data <- data.frame(variable = c(95, 96, 97,98,99), date=c(1,2,3,4,5))
data$variableUpdated <- year(as.Date(as.character(data$variable), format="%y"))

and only with base R 并且仅在基数为R的情况下

data$variableUpdated <- format(as.Date(as.character(data$variable), format="%y"),"%Y")

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

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