How to convert the below in character to Date format?
YYYY.MM
I am facing an issue dealing with zeroes after decimal points for month 10. Say
2012.10
appears in my input source data as
2012.1
with the zero post decimal missing. How do I bring this back in the Date format?
Since you have only year
and month
, you need to assign some value for day
before you convert to date. In the example below, the day has arbitrarily been chosen as 15
.
IF THE INPUT IS CHARACTER
dates = c("2012.10", "2012.01")
lubridate::ymd(paste0(year_month = dates, day = "15"))
#[1] "2012-10-15" "2012-01-15"
IF THE INPUT IS NUMERIC
dates = c(2012.10, 2012.01)
do.call(c, lapply(strsplit(as.character(dates), "\\."), function(d){
if(nchar(d[2]) == 1){
d[2] = paste0(d[2],"0")
}
lubridate::ymd(paste0(year = d[1], month = d[2], day = "15"))
}))
#[1] "2012-10-15" "2012-01-15"