How to useseq() method in R Language
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
# defining start date date <- as.Date ( "2021/08/04" ) # defining length of range len <- 9 # generating range of dates 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
# defining start date start_date <- as.Date ( "2021/08/04" ) # defining end date end_date <- as.Date ( "2021/08/11" ) # generating range of dates 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β
How to Create a Range of Dates in R
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.
Contact Us