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?
Indeed, as has been mentioned above (and elsewhere on SO), in order to convert the string to a date, you need a specific date of the month. From the
as.Date()
manual page:A simple solution would be to paste the date
"01"
to each date and usestrptime()
to indicate it as the first day of that month.For those seeking a little more background on processing dates and times in R:
In R, times use
POSIXct
andPOSIXlt
classes and dates use theDate
class.Dates are stored as the number of days since January 1st, 1970 and times are stored as the number of seconds since January 1st, 1970.
So, for example:
To perform operations on dates and times:
And to process dates, you can use
strptime()
(borrowing these examples from the manual page):