format year-month to POSIXct [duplicate]

Solution 1:

That's a FAQ: a date is comprised of day, month and year. You are missing one part. So by adding a day, say, '-01', you can impose the missing string structure and parse. Or you can use a more tolerant parser:

R> library(anytime)
R> anydate("2017-06")
[1] "2017-06-01"
R> 

Which works for your data too:

R> date
 [1] "2016-03" "2016-04" "2016-05" "2016-06"
 [5] "2016-07" "2016-08" "2016-09" "2016-10"
 [9] "2016-11" "2016-12"
R> anydate(date)
 [1] "2016-03-01" "2016-04-01" "2016-05-01"
 [4] "2016-06-01" "2016-07-01" "2016-08-01"
 [7] "2016-09-01" "2016-10-01" "2016-11-01"
[10] "2016-12-01"
R> 

Lastly, your request for POSIXct type is still short an hour, minute and second. But by the same principle:

R> anytime(date)
 [1] "2016-03-01 CST" "2016-04-01 CDT"
 [3] "2016-05-01 CDT" "2016-06-01 CDT"
 [5] "2016-07-01 CDT" "2016-08-01 CDT"
 [7] "2016-09-01 CDT" "2016-10-01 CDT"
 [9] "2016-11-01 CDT" "2016-12-01 CST"
R> 

These two functions return proper Date and POSIXct types, respectively.