I have a csv file with dates as characters in the following format: 202211, 202210, 202209 etc.
I tried using
xdate<- as.Date("202211", format="%Y%m")
xdate
but the output I get is NA
This works if the format would be 20221111
xdate<- as.Date("20221111", format="%Y%m%d")
xdate
[1] "2022-11-11"
Is there a way to solve this problem without adding a day to the dates?
CodePudding user response:
If your date is always the first day of month, then you can paste "01" at the end of the string and then apply as.Date
xdate<- as.Date(paste0("202211", "01"), format="%Y%m%d")
xdate
[1] "2022-11-01"
CodePudding user response:
Using lubridate avoids manually adding a day to the dates:
library(lubridate)
ym("202211")
[1] "2022-11-01"