Home > Mobile >  lubridate month vector generation with NA on 31.08.2022
lubridate month vector generation with NA on 31.08.2022

Time:09-01

How can I avoid that this statement gets NA for september when run on the 31.08.2022?

format(lubridate::as_date(as.character(lubridate::now()   months(-1:2))), "%m.%Y")
[1] "07.2022" "08.2022" NA        "10.2022"

CodePudding user response:

I found Add and subtract months to a date without exceeding the last day of the new month

format(lubridate::as_date(as.character(lubridate::now() %m % months(-1:2))), "%m.%Y")
[1] "07.2022" "08.2022" "09.2022" "10.2022"

CodePudding user response:

Use dmonths instead of months, I also removed some redundant code. This will do:

format(now()   dmonths(-1:2), "%m.%Y")
# [1] "07.2022" "08.2022" "09.2022" "10.2022"
  • Related