subtract months from a date in R

How to add or subtract months from a date in R

If you want to add or subtract months from a date in R, it might sound simple, but some situations are worth considering. Even though the lubridate package has function months that you can use to subtract months, you might get NA in the result. That is usually the case with the last dates of the month, which leads to impossible dates from another month.

 

For example, here are the last two dates of May.

d1 <- as.Date("2022-05-30")

d2 <- as.Date("2022-05-31")

If I’m subtracting one month from the first of the dates, it works because there is also the same day number in April. The same applies to the addition of one month.

require(lubridate)

d1 - months(1)

#[1] "2022-04-30"

In the same situation with another date, I’m getting NA when subtracting one month because there are not 31 days in April. The same problem happens when adding one month to date. The possible number of days is exceeded.

d2 - months(1)
#[1] NA

d2 + months(1)
#[1] NA

 

Add or subtract months from a date in R with lubridate

 

With the help of the lubridate, you can do addition and subtraction calculation with months in R easily. The function months from the lubridate might be confusing because there is a base function with the same name, and there is a particular operator for addition or subtraction.

If you want to subtract one month from a date in R, it looks like this.

require(lubridate)

d2 <- as.Date("2022-05-31")

d2 %m-% months(1)

#[1] "2022-04-30"

You can change the number of the month and get, for example, a relevant date half a year ago.

Here is an addition.

d2 %m+% months(1)

#[1] "2022-06-30"

You can also use one of the rollback functions from the lubridate within the previous examples.

add_with_rollback(d2, -months(1))

#[1] "2022-04-30"

add_with_rollback(d2, months(1))

#[1] "2022-06-30"

 

Here are a couple of other calculations with dates in this blog that might be interesting. For example, add or subtract days from date or DateTime in R or calculation of last or first date of the month.





Posted

in

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *