Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

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?

question from:https://stackoverflow.com/questions/65893120/customize-the-year-in-as-date-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...