The date variable/column in a dataset is of utmost importance in terms of carrying out a Time series analysis and exploratory data analysis.
In R, most of the times a Date-format variable is read as a character type from any dataset. If you want to carry out any sort of analysis w.r.t dates then you must convert this character type variable to date.
In this Recipe, you will learn how to find the difference between two dates in R
We will create 2 date variable in Date format (YYYY-MM-DD) using as.Date()
date_1 = as.Date("2020-05-01") date_2 = as.Date("2020-06-01")
We will use difftime() function to carry out this task.
Syntax: difftime(date1, date2, units = )
diff_dates = difftime(date_2,date_1, units = "days") diff_dates
Time difference of 31 days
Note: we mostly convert the difference in terms of a numeric value by using as.numeric() function
diff_dates = as.numeric(diff_dates) diff_dates