You can use one of the following two methods to calculate the number of months between two dates in R:
Method 1: Calculate Number of Whole Months Between Dates
library(lubridate)
interval(first_date, second_date) %/% months(1)
Method 2: Calculate Number of Partial Months (With Decimal Places) Between Dates
library(lubridate)
interval(first_date, second_date) %/% days(1) / (365/12)
The following examples show how to use each method in practice.
Example 1: Calculate Number of Whole Months Between Dates
We can use the following code to calculate the number of whole months between two dates in R:
library(lubridate) #define dates first_date Date('2022-05-01') second_date Date('2022-09-04') #calculate difference between dates in months diff 1) #view difference diff [1] 4
We can see that there are four whole months between the two dates that we specified.
Example 2: Calculate Number of Partial Months Between Dates
We can use the following code to calculate the number of partial months between two dates in R:
library(lubridate) #define dates first_date Date('2022-05-01') second_date Date('2022-09-04') #calculate difference between dates in partial months diff 1) / (365/12) #view difference diff [1] 4.142466
We can see that there are 4.142466 months between the two dates that we specified.
Note how this method is more specific than the previous method because it tells us the number of partial months between the dates as well.
Depending on your situation, you may prefer to use one of these methods over the other.
Note: Both methods use functions from the lubridate package in R. If you don’t already have this package installed, you can run the following in your R console:
install.packages('lubridate')
You can also find the complete documentation for the interval() function we used here.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Convert a Character to a Timestamp in R
How to Convert Factor to Date in R
How to Extract Year from Date in R