Reputation:
Tried to make a factor to date.
X:
Jul-15
Jul-15
Jul-15
Jul-15
Aug-16
I want to convert them to a date.
X <- as.Date(Xx, format="%b-%y")
Results in NA's.
This was my source for the code: https://www.r-bloggers.com/date-formats-in-r/
Upvotes: 1
Views: 459
Reputation: 638
The yearmon
function from the zoo
package will help you here. Since you have lubridate
as a tag on the question, we can then use as_date
from the lubridate
package to turn it into a date object. The base function as.Date
will work as well.
library(zoo)
library(lubridate)
as_date(as.yearmon(Xx, "%b-%y"))
[1] "2015-07-01" "2015-07-01" "2015-07-01" "2015-07-01" "2016-08-01"
If you want to leave them as yearmon class, you can just run:
as.yearmon(Xx, "%b-%y")
[1] "Jul 2015" "Jul 2015" "Jul 2015" "Jul 2015" "Aug 2016"
Upvotes: 0
Reputation: 2416
You need a complete date, with day :
library(lubridate)
X <- "Jul-15"
X <- paste("01", X, sep="-")
dmy(X)
Upvotes: 0
Reputation: 1121
as.Date is the base R function, as_date is the lubridate function, but this is not your problem
Without a day, you're not completely specifying the date completely. Unlike year, where R will fill in with the current year, this does not appear to happen for a missing day
As a workaround, run:
X <- as.Date(paste0(Xx,'-01'), format="%b-%y-%d")
Which will set the dates to be the first of the month
Upvotes: 2