Converting year and month ("yyyy-mm" format) to a date?

R_User picture R_User · Jun 5, 2011 · Viewed 134.9k times · Source

I have a dataset that looks like this:

Month    count
2009-01  12
2009-02  310
2009-03  2379
2009-04  234
2009-05  14
2009-08  1
2009-09  34
2009-10  2386

I want to plot the data (months as x values and counts as y values). Since there are gaps in the data, I want to convert the Information for the Month into a date. I tried:

as.Date("2009-03", "%Y-%m")

But it did not work. Whats wrong? It seems that as.Date() requires also a day and is not able to set a standard value for the day? Which function solves my problem?

Answer

Sacha Epskamp picture Sacha Epskamp · Jun 5, 2011

Since dates correspond to a numeric value and a starting date, you indeed need the day. If you really need your data to be in Date format, you can just fix the day to the first of each month manually by pasting it to the date:

month <- "2009-03"
as.Date(paste(month,"-01",sep=""))