If you really do just want to convert it to "Date"
class using the first of the month, then Roland's solution seems most direct but there are some other considerations such as whether you might want to use end of month or whether you really want to represent year-months using dates in the first place.
The zoo package has a "yearmon"
class which can represent year-months directly without converting them to dates and also has the as.Date.yearmon
method which has a frac=
argument can be used to specify the fraction of the way through the month to convert to if you do want "Date"
class.
First, make sure that the dates are character strings. The input in the question shows 1993.10 as one of the inputs so we must make sure that there is a trailing zero. (If the inputs are already character with the trailing zero then this is not a problem. We have assumed the worst case here assuming numeric so that we need to explicitly convert them to character stings with a trailing 0 if need be.) Now use as.yearmon
with format "%Y.%m"
. Finally use as.Date.yearmon
to convert to "Date"
class.
Perhaps the biggest advantage of this approach is that we could just leave the result in "yearmon"
class (i.e. omit the "as.Date"
part, e.g. as.yearmon(sprintf("%.2f", dates))
or if the dates were already character strings, dates.ch
, with a trailing 0 in the case of "1993.10"
then just as.yearmon(dates.ch, "%Y.%m")
, which really represent what you have better since the day is not really meaningful given that it was not there at the beginning. "yearmon"
objects can be plotted and sorted in the expected manner.
Here is the conversion to "Date"
class using "yearmon"
:
library(zoo)
dates <- c(1993.07, 1993.08, 1993.09, 1993.1, 1993.11, 1993.12) # test input
as.Date(as.yearmon(sprintf("%.2f", dates), "%Y.%m")) # 1st of month
## [1] "1993-07-01" "1993-08-01" "1993-09-01" "1993-10-01" "1993-11-01" "1993-12-01"
as.Date(as.yearmon(sprintf("%.2f", dates), "%Y.%m"), frac = 1) # last of month
## [1] "1993-07-31" "1993-08-31" "1993-09-30" "1993-10-31" "1993-11-30" "1993-12-31"
or if the test input looks like this:
dates.ch <- c("1993.07", "1993.08", "1993.09", "1993.10", "1993.11", "1993.12") # input
as.Date(as.yearmon(dates.ch, "%Y.%m"))
as.Date(as.yearmon(dates.ch, "%Y.%m"), frac = 1)