In this article, we will discuss how to Find the number of months between two dates in the R programming language.
Example:
Input: Date_1 = 2020/02/21
Date_2 = 2020/03/21
Output: 1
Explanation: In Date_1 and Date_2 have only one difference in month.
Here we will use seq() function to get the result. This function is used to create a sequence of elements in a Vector. It takes the length and difference between values as optional argument.
Syntax: length(seq(from=date_1, to=date_2, by=’month’)) -1
Where: seq is function generates a sequence of numbers, from is starting date, to is ending date.
Example 1: In the below example, we are storing two dates in two different variables and by using length(seq(from=date_1, to=date_2, by=’month’)) we are finding a number of months between these two dates.
R
date_1<- as.Date ( "2020-08-10" )
date_2<- as.Date ( "2020-10-10" )
a = seq (from = date_1, to = date_2, by = 'month' ))
length (a)-1
|
Output:
2
Example 2: Checking with different dates.
R
date_1<- as.Date ( "2020-01-23" )
date_2<- as.Date ( "2020-9-25" )
a= seq (from = date_1, to = date_2, by = 'month' ))
length (a)-1
|
Output:
8