Convert a yyyymm-integer to date

时间:2016-04-25 09:16:11

标签: r date integer

I would like to convert a YYYYMM-integer to a Date without converting it to character (=is there a mdy-function like in SAS?). I would like to replace this code:

 dateint<-201511
 datestr<-paste(toString(dateint,length=8),'01')
 date<-as.Date(datestr,'%Y%m%d')
 print(date)
 class(date)

with a working version of this. If possible the resulting class should be a date too:

 year<-dateint %% 100
 month<-floor(dateint/100)
 date2<-ISOdate(year,month,1) # I can't make this work ..
 print(date2)
 class(date2)

Thanks & kind regards

1 个答案:

答案 0 :(得分:5)

The package lubridate has a function ymd, which accepts numeric input:

> library(lubridate)
> ymd(20151101)
[1] "2015-11-01 UTC"

You need however to add the day at the end.