1

So I have this long dataset, where in one column I have a date specified as character in format YYYMMM, but month abbreviated. So for example 1995MAR, 1995APR and so on. How can I transform that to date format?

I tried as.Date but it obviously hasn't worked, and with lubridate::ymd which hasn't worked as well.

matfan
  • 11
  • 1

2 Answers2

2

Using parse_date_time from lubridate

date <- "1995MAR"
library(lubridate)
parse_date_time(date, order = "Yb")

Output:

[1] "1995-03-01 UTC"

Alternatively using zoo

library(zoo)
as.Date(as.yearmon(date, '%Y%b'))

Output:

"1995-03-01"

str(as.Date(as.yearmon(date, '%Y%b')))

Date[1:1], format: "1995-03-01"
cgvoller
  • 873
  • 1
  • 14
  • The output chunk needs to be fixed too to correspond to the input shown. – G. Grothendieck Dec 05 '22 at 14:04
  • Perfect, that works like a charm. I do want to ask for additional example, if I only have a year, so in some instances I have just 2002 for example. I tried with parse_date_time(date, order = "Y"), but no sucess... – matfan Dec 05 '22 at 14:19
  • @matfan if you add the argument truncated=2L to the parse_date_time does that work for your year only date? – cgvoller Dec 05 '22 at 14:30
  • If you have a character vector in which some entries are year/month in the format shown in the question and some entries just have the year such as `x <- c("2000MAR", "2001")` then this will convert them all to Date class `as.Date(as.yearmon(paste0(x, "Jan"), "%Y%b"))` as it ignores junk on the end or omit the `as.Date` to get all yearmon entries.. – G. Grothendieck Dec 06 '22 at 00:27
1

In Base R, add a day number to parse:

date <- "1995MAR"
as.Date(paste(date, "01"), format = "%Y%b %d")
#[1] "1995-03-01"
Maël
  • 45,206
  • 3
  • 29
  • 67