I have a data vector that looks like this:
dates<-c("2014-11", "2014-12", "2015-01", "2015-02", "2015-03", "2015-04")
I am trying to convert it into a recognizable date format, however no luck:
as.Date(dates,"%Y-%m")
[1] NA NA NA NA NA NA
I suspect that the problem lies in that that there is no day specified.
Any thoughs of how this can be solved?
If we need to convert to Date
class, it needs a day. So, we can paste
with one of the days of interest, say 1, and use as.Date
as.Date(paste0(dates, "-01"))
The zoo package has a nice interface to this, which allows storing of year-month data and a as.Date
method to coerce to a Date
object. For example:
library("zoo")
dates <- c("2014-11", "2014-12", "2015-01", "2015-02", "2015-03", "2015-04")
The function to convert the character vector or year-months into a yearmon
is as.yearmon
. The second argument is the format of the date parts in the individual strings. Here I use
%Y
for year with century%m
for the month as a decimal-
.
yrmo <- as.yearmon(dates, "%Y-%m")
This gives
> yrmo
[1] "Nov 2014" "Dec 2014" "Jan 2015" "Feb 2015" "Mar 2015" "Apr 2015"
This is actually the default, so you can leave off the format part entirely, e.g. yrmo <- as.yearmon(dates)
To convert to a Date
class object, the as.Date
method is used
> as.Date(yrmo)
[1] "2014-11-01" "2014-12-01" "2015-01-01" "2015-02-01" "2015-03-01"
[6] "2015-04-01"
This method has a second argument frac
which is specified allows you to state how far through the month you want each resulting Date
element to be (how many days as a fraction of the length of the month in days)
> as.Date(yrmo, frac = 0.5)
[1] "2014-11-15" "2014-12-16" "2015-01-16" "2015-02-14" "2015-03-16"
[6] "2015-04-15"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With