Reputation: 83
Just a brief (and hopefully simple!) question;
I have a column of dates such as 08/14
and 08/15
. However the column class is character
, and I was wondering if it is possible (and if so how) to convert this into a date class? I've tried lots of different ways and it either does nothing, or returns N/A
values for the whole column. Hopefully there should be a simple line of code to fix this that I haven't come across yet?
Any help much appreciated!!
Upvotes: 1
Views: 125
Reputation: 444
library(dplyr)
dates <- c("08/14", "10/13", "12/09") # year-month
datesWithYear <- paste(date, "/01", sep = "") %>%
as.Date()
If you want to use the year-month combination as a factor for cohort analysis of something similar you can always use as.yearmon()
from the zoo
package. tsibble
and lubridate
also have interesting functions for dealing with dates and time.
Upvotes: 1
Reputation: 886948
One option is to create a day by paste
ing and then use as.Date
because date also needs day info
as.Date(paste0(c("08/14", "08/15"), "/01"), format = "%m/%y/%d")
#[1] "2014-08-01" "2015-08-01"
Or make use of as.yearmon
from zoo
library(zoo)
as.Date(as.yearmon(c("08/14", "08/15"), "%m/%y"))
Upvotes: 3