Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to calculate Years between Dates in R ?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In this article, we will discuss how to calculate the number of years or difference of years between two dates in R programming language.

Example:

Input: 

Date_1 = 2020/02/21

Date_2 = 2023/03/21

Output:

3

Explanation: 

In Date_1 and Date_2 have three years difference in year.

Here we will use seq() function to get the result. This function is used to create a sequence of elements in a Vector.

Syntax: 

length(seq(from=date_1, to=date_2, by=’year’)) -1  

Example 1: 

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("2023-10-10")
  
# Here first date will start from
# 2020-08-10 and end by 2023-10-10.
# Here increment is done by year.
# This three dates will be generated
# as we used eq and this dates will
# be stored in a.
a = seq(from = date_1, to = date_2, by = 'year')
  
# Here we are finding length of a and
# we are subtracting 1 because we dont
# need to include current year.
length(a)-1

Output:

3

Example 2:

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("2100-08-10")
 
# Here first date will start from
# 2020-08-10 and end by 2100-08-10.
# Here increment is done by year.
# 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 = 'year')
 
# Here we are finding length of a and
# we are subtracting 1 because we dont
# need to include current year.
length(a)-1

 
Output:

80

 


My Personal Notes arrow_drop_up
Last Updated : 14 May, 2021
Like Article
Save Article
Similar Reads
Related Tutorials