How to Create a Range of Dates in R (Example)
In this post you’ll learn how to generate a date range in R programming.
The page contains these contents:
Let’s get started…
Example: Generating a Range of Dates in R
Let’s assume that we want to create a date range with all days starting from the 20th of October 2020. Then we have to create a date object containing our starting date first:
start_date <- as.Date("2020/10/05") # Create example date
Now, we can create a range of dates with the seq function as follows:
seq(start_date, by = "day", length.out = 5) # Get Range with 5 dates 2020-10-05" "2020-10-06" "2020-10-07" "2020-10-08" "2020-10-09"
As you can see based on the previous R code, we have to specify three components within the seq command:
- The starting date (as created previously)
- The interval (i.e. we want to return R the date of each day)
- The length of the range (i.e. 5 days)
That’s it. Now, you can modify the seq function according to your needs.
Video & Further Resources
Would you like to know more about the creation of date intervals, ranges, and daily time series objects? Then you may have a look at the following video which I have published on my YouTube channel. I illustrate the example of this article 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.
Furthermore, I can recommend reading the other posts on my website:
- Convert Date to Day of Week in R
- Convert Date to Numeric Time Object in R
- R Functions List (+ Examples)
- The R Programming Language
In summary: In this R tutorial you learned how to generate a vector containing a regular sequences of dates. In case you have further comments and/or questions, let me know in the comments section.
Statistics Globe Newsletter