how to covert dates with just year-month into year-month-date in R?

Viewed 59

I have a list of program dates as character strings in the following format

program.date.have <-c('Sep-14','Aug-14','Sep-16')

I am assuming that all these programs started on the first day of each month, and I want the program.date to end up like

program.date.want<-c('2014-09-01', '2014-08-01, '2016-09-01') or in YYYY-MM-DD format.

To start somewhere I have decided to covert the character strings into the date format in the following way

program.date.have<-c('Sep-14','Aug-14','Sep-16')
betterDates <- as.Date(program.date,
                       format = "%m-%y")

But even that does not seem to work. how do I use values in program.date variable to be converted into format I want in program.date.want

1 Answers

We can use as.yearmon from zoo, specify the format, and wrap with as.Date which automatically generates the 'day' as the first of the month.

library(zoo)
as.Date(as.yearmon(program.date.have, "%b-%y"))
#[1] "2014-09-01" "2014-08-01" "2016-09-01"

Or a base R option is to paste the '01' at the start or end and then specify the appropriate format in as.Date

as.Date(paste0(program.date.have, "-01"), "%b-%y-%d")
#[1] "2014-09-01" "2014-08-01" "2016-09-01"
Related