How to use the difftime function In R Language

R




# Example dates
date1 <- as.Date("2021-01-01")
date2 <- as.Date("2023-08-01")
 
# Calculate the difference in weeks
weeks_diff <- difftime(date2, date1, units = "weeks")
print(weeks_diff)
 
# Calculate and print the year difference
year_diff <- weeks_diff / 52
print(paste('Year difference:', year_diff))
 
# Calculate the difference in days
days_diff <- difftime(date2, date1, units = "days")
print(days_diff)
# Calculate and print the year difference
year_diff <- days_diff / 365
print(paste('Year difference:', year_diff))


Output:

Time difference of 134.5714 weeks
[1] "Year difference: 2.58791208791209"
Time difference of 942 days
[1] "Year difference: 2.58082191780822"

How to calculate Years between Dates in R ?

To calculate the number of years between two dates we have several methods. In this article, we will discuss all the methods and their examples of how to calculate the number of years or the difference of years between two dates in the R Programming Language.

Table of Content

  • Method 1: Using the seq() function
  • Method 2: Using the difftime function
  • Method 3: Using the base R as.POSIXlt function

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 the 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  

Similar Reads

Method 1: Using the seq() function

...

Method 2: Using the difftime function

Example 1:...

Method 3: Using the base R as.POSIXlt function

...