How to create a date range in R

From two integers (1, 5) you can create a range as follows

 1:5 

[1] 1 2 3 4 5

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

The exit should be

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

+5
date r
source share
4 answers

Does it 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 something about time zones

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 "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" 
+15
source share

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" 
+7
source share

Here's the answer, admittedly, worse than @jalapic, which doesn't use seq and uses the for loop instead:

 date1 <- "2014-09-04" date2 <- "2014-09-11" dif <- as.numeric(abs(as.Date(date1) - as.Date(date2))) dates <- vector() for (i in 1:dif) { date <- (as.Date(date1) + i) dates <- append(dates, date) } # [1] "2014-09-05" "2014-09-06" "2014-09-07" "2014-09-08" "2014-09-09" "2014-09-10" "2014-09-11 
0
source share

here is a snapshot although JST timezone is not recognized by my system

 d1<-ISOdate(year=2014,month=9,day=4,tz="GMT") seq(from=d1,by="day",length.out=5) [1] "2014-09-04 12:00:00 GMT" "2014-09-05 12:00:00 GMT" "2014-09-06 12:00:00 GMT" "2014-09-07 12:00:00 GMT" "2014-09-08 12:00:00 GMT" 
0
source share

All Articles