rlubridate

Which function can I to add 12 months to 2024-02-29 to get a value?


My code runs but I get an NA for 2024-02-29

library(lubridate)
my_date <- c(as.Date("2024-01-29"), as.Date("2024-02-29"))
next_year <- my_date+months(12)
next_year
#> [1] "2025-01-29" NA

Solution

  • Assuming, you are looking for +1 day then, you can overcome that with an is.na()-check:

    > library(lubridate)
    > my_date = c(as.Date("2024-01-29"), as.Date("2024-02-29"))
    > next_year = my_date + months(12)
    > next_year
    [1] "2025-01-29" NA          
    > next_year = if(any(is.na(next_year))) my_date + is.na(next_year) + months(12)
    > next_year
    [1] "2025-01-29" "2025-03-01"