Find number of months between two dates in R
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
# creating date_1 variable and storing date in it.date_1<-as.Date("2020-08-10")# creating date_2 variable and storing date in it.date_2<-as.Date("2020-10-10")# Here first date will start from 2020-08-10 and# end by 2020-10-10.Here increment is done by month.# This three dates will be generated as we used# seq and this dates will be stored in a. a = seq(from = date_1, to = date_2, by = 'month'))# Here we are finding length of a and we are subtracting# 1 because we dont need to include current month.length(a)-1 |
Output:
2
Example 2: Checking with different dates.
R
# creating date_1 variable and storing date in it.date_1<-as.Date("2020-01-23")# creating date_2 variable and storing date in it.date_2<-as.Date("2020-9-25")# Here first date will start from 2020-01-23# and end by 2020-9-25.Here increment is done# by month.This three dates will be generated# as we used seq and this dates will be stored in a. a=seq(from = date_1, to = date_2, by = 'month'))# Here we are finding length of a and we are# subtracting 1 because we dont need to include# current month.length(a)-1 |
Output:
8


