I am trying to create a future data frame which contains date with month frequency in an another data frame.
The data I am using is given below dput(date):
c("2021-10-01", "2021-11-01", "2021-12-01", "2022-01-01", "2022-02-01",
"2022-03-01", "2022-04-01", "2022-05-01", "2022-06-01", "2022-07-01",
"2022-08-01")
The expected result which I was trying to achieve is to create set a frequency which can be mentioned like this,
freq = 9
and then generates dates for the next 9 months in a data frame, like 2022-09-01 to 2023-09-01?
Any help is appreciated.
Thank you.
CodePudding user response:
You have several options: here's one with lubridate::months
.
library(lubridate)
dates <- c("2021-10-01", "2021-11-01", "2021-12-01", "2022-01-01", "2022-02-01",
"2022-03-01", "2022-04-01", "2022-05-01", "2022-06-01", "2022-07-01",
"2022-08-01")
max(ymd(dates)) %m % months(1:9)
#[1] "2022-09-01" "2022-10-01" "2022-11-01" "2022-12-01" "2023-01-01" "2023-02-01" "2023-03-01" "2023-04-01" "2023-05-01"
Or with seq
:
seq(max(ymd(dates)), by = "month", length.out = 9)
Or with clock::add_months
:
library(clock)
add_months(max(ymd(dates)), 1:9)