Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a range of dates in R

Tags:

From two integers (1, 5) one can create a range in the following way

1:5 

[1] 1 2 3 4 5

How can you make a range of dates if you are give two dates ("2014-09-04 JST", "2014-09-11 JST")

The output must be

[1] ("2014-09-04 JST", "2014-09-05 JST", "2014-09-06 JST", "2014-09-07 JST", "2014-09-08 JST")

like image 656
sjdh Avatar asked Sep 05 '14 00:09

sjdh


People also ask

How do I create a date sequence in R?

To create a sequence of dates we can leverage the seq() function. As with numeric vectors, you have to specify at least three of the four arguments ( from , to , by , and length. out ).

What does range () do in R?

In R programming language range is an efficient way of finding the difference between maximum and minimum values within a vector or a data frame. A range () function is defined as the interval between the largest (maximum) and smallest (minimum) data value within a vector or column in a data frame in R.


2 Answers

Does this help?

seq(as.Date("2014/09/04"), by = "day", length.out = 5) # [1] "2014-09-04" "2014-09-05" "2014-09-06" "2014-09-07" "2014-09-08" 

edit: adding in something about timezones

this works for my current timezone

seq(c(ISOdate(2014,4,9)), by = "DSTday", length.out = 5)  #[1] "2014-04-09 08:00:00 EDT" "2014-04-10 08:00:00 EDT" "2014-04-11 08:00:00 EDT" "2014-04-12 08:00:00 EDT" #[5] "2014-04-13 08:00:00 EDT" 

edit2:

OlsonNames()  # I used this to find out what to write for the JST tz - it's "Japan"  x <- as.POSIXct("2014-09-04 23:59:59", tz="Japan") format(seq(x, by="day", length.out=5), "%Y-%m-%d %Z")  # [1] "2014-09-04 JST" "2014-09-05 JST" "2014-09-06 JST" "2014-09-07 JST" "2014-09-08 JST" 
like image 105
jalapic Avatar answered Sep 23 '22 16:09

jalapic


To get a sequence of dates ( days, weeks,.. ) using only start and end dates you can use:

seq(as.Date("2014/1/1"), as.Date("2014/1/10"), "days”)  [1] "2014-01-01" "2014-01-02" "2014-01-03" "2014-01-04" "2014-01-05" "2014-01-06" "2014-01-07" [8] "2014-01-08" "2014-01-09" "2014-01-10” 
like image 26
hvollmeier Avatar answered Sep 20 '22 16:09

hvollmeier