1

I have some dates (character string) with only month and date, for example "20-May". I'm using as.Date to convert it to a date object:

as.Date("20-May", format = "%d-%b")

What I got is: "2021-05-20". So R automatically sets the year to the current year. But I want to customize the year to 2019 (expect the output to be "2019-05-20"). How to do that?

Xiaokang
  • 331
  • 1
  • 11

1 Answers1

2

A Date involves 'year', 'month' and 'day'. If one of them is not specified i.e. the 'year', it gets the current 'year'. Avoid that by pasteing the 'year' and specify the four-digit year format (%Y)

as.Date(paste0("20-May", "-2019"), format = "%d-%b-%Y")
#[1] "2019-05-20"

Or another option is to change the year by assigning

library(lubridate)
date1 <- as.Date("20-May", format = "%d-%b")
year(date1) <- 2019
date1
#[1] "2019-05-20"
akrun
  • 874,273
  • 37
  • 540
  • 662