How to Create a Range of Dates in R
Last Updated :
23 Aug, 2021
R programming language makes it extremely easy to generate range of integers as well as singular characters. It is also possible to store Date objects in R in different formats and increment the sequentially to produce a range using both base packages as well external ones.
This article discusses various ways by which a range of dates can be defined.
The date objects are stored as the number of days calculated starting January 1, 1970, where negative numbers are used to refer to earlier dates. The Date objects support basic arithmetic directly, where in the integers are added or subtracted directly from the Dates. The Date object can also specify different formats to contain the dates.
The as.Date() method takes as input a character date object and converts it to a Date object.
Syntax:
as.Date(character date object)
The seq() method in R can be used to generate regular sequences which are incremental or detrimental sequentially arranged. The “by” parameter may contain strings or integers to increment the sequence by.
Syntax:
seq(from, to, by, length.out)
Parameter:
- from – Beginning of the sequence
- to – End of the sequence
- by – The steps to increment the sequence by
- length.out – The total length of the sequence
Thus by combining these two methods we can easily get the job done. seq() will increment each entry by 1.
Example: Creating a range of dates
R
date <- as.Date ( "2021/08/04" )
len <- 9
seq (date, by = "day" , length.out = len)
|
Output
[1] “2021-08-04” “2021-08-05” “2021-08-06” “2021-08-07” “2021-08-08”
[6] “2021-08-09” “2021-08-10” “2021-08-11” “2021-08-12”
Example: Code snippet that defines a start and end date and incrementing each entry by the number of “days” and adding entries by adding days.
R
start_date <- as.Date ( "2021/08/04" )
end_date <- as.Date ( "2021/08/11" )
range <- seq (start_date, end_date, "days" )
print (range)
|
Output
[1] “2021-08-04” “2021-08-05” “2021-08-06” “2021-08-07” “2021-08-08”
[6] “2021-08-09” “2021-08-10” “2021-08-11”
Method 2: Using lubridate package
Lubridate package in R is used to work with date and time objects. It makes it easier to parse and manipulate the objects and needs to be installed and loaded into the working space by the following command :
install.packages("lubridate")
The ymd() method can be used to convert a character date to a date format consisting of year-month-date using the lubridate package. This is followed by the application of seq() method of base R.
Example: Creating a range of dates
R
library ( "lubridate" )
start_date <- ymd ( "2021/08/04" )
end_date <- ymd ( "2021/08/11" )
range <- seq (start_date, end_date, "days" )
print (range)
|
Output
[1] “2021-08-04” “2021-08-05” “2021-08-06” “2021-08-07” “2021-08-08”
[6] “2021-08-09” “2021-08-10” “2021-08-11”
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...