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

How to create future dates with Month frequency in R

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") 

enter image description here

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

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?

enter image description here

Any help is appreciated.

Thank you.

>Solution :

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)
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