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.
CodePudding user response:
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"