简体   繁体   中英

Customize the year in as.Date (in R)

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?

A Date involves 'year', 'month' and 'day'. If one of them is not specified ie the 'year', it gets the current 'year'. Avoid that by paste ing 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM