Find Earliest & Latest Date in R (Example)
In this tutorial you’ll learn how to determine the maximum and minimum dates of a vector in the R programming language.
The content of the tutorial looks as follows:
Let’s just jump right in.
Introduction of Example Data
The first step is to construct some data that we can use in the examples later on:
my_dates <- c("2022-05-17", "2021-07-27", "2024-11-08", # Create character dates "2022-01-12", "2021-08-21", "2022-09-13") my_dates # Print character dates #  "2022-05-17" "2021-07-27" "2024-11-08" "2022-01-12" "2021-08-21" "2022-09-13"
Have a look at the previous output of the RStudio console. It shows that our example data is a vector of dates.
Example: Get Minimum & Maximum Date Using as.Date, min & max Functions
In this example, I’ll illustrate how to extract the earliest and latest dates from our example vector.
For this, we first have to check the data type of our example data using the class function:
class(my_dates) # Check class of dates #  "character"
At this point, our example data has the character class.
my_dates_updated <- as.Date(my_dates) # Convert character to Date my_dates_updated # Print updated dates #  "2022-05-17" "2021-07-27" "2024-11-08" "2022-01-12" "2021-08-21" "2022-09-13"
The previous R syntax has created a new vector object called my_dates_updated, which looks exactly the same as the original character vector.
However, we can see the difference by applying the class function to our updated vector object:
class(my_dates_updated) # Check class of updated dates #  "Date"
Our new vector object has the Date class!
Now, we can apply the min and max functions to find the earliest and latest dates of our vector.
The min function returns the minimum date…
min(my_dates_updated) # Earliest date #  "2021-07-27"
…and the max function displays the maximum date:
max(my_dates_updated) # Latest date #  "2024-11-08"
Video & Further Resources
Have a look at the following video of my YouTube channel. I’m explaining the R programming codes of this tutorial in the video:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Additionally, you may have a look at the other tutorials of this homepage. Some tutorials about dates can be found here:
- Order Data Frame by Date in R
- Convert Factor to Date in R
- Number of Months Between Two Dates
- The R Programming Language
To summarize: At this point you should know how to return the earliest and latest date of a date vector in the R programming language. Note that we could apply the same R code to the column of a data frame.
In case you have further questions, please let me know in the comments below. Furthermore, don’t forget to subscribe to my email newsletter for updates on new articles.
Statistics Globe Newsletter