Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find the first day of specific years ago from current day using lubridate package

I’m able to find the date certain years ago from today with code below:

library(lubridate)
today <- format(Sys.Date())
pre_3years <- ymd(today) - years(3)
pre_3years 

Out:

[1] "2018-12-27"

In fact, I hope to get the first day of pre_3year, which is 2018-01-01 for this example, how could I get that using lubridate package in R? Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You may use floor_date from lubridate to get 1st day of the year.

library(lubridate)
first_day_of_n_prev <- function(x) {
  floor_date(Sys.Date() - years(x), 'year')  
}

first_day_of_n_prev(3)
#[1] "2018-01-01"

first_day_of_n_prev(2)
#[1] "2019-01-01"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading