1

I am new to R and I would like to create a vector between 2 dates a

Here is my code

 start.plot <- c("2011-01-01", "2012-12-31")
 plot1 <- substr(start.plot[1],1,7)
 plot2 <- substr(start.plot[2],1,7)

 Month_test <- as.character(seq(as.Date(start.plot[1]), as.Date(start.plot[2]), by="months"))

and here is the result of this code

 [1] "2011-01-01" "2011-02-01" "2011-03-01" "2011-04-01" "2011-05-01" "2011-06-01"
 [7] "2011-07-01" "2011-08-01" "2011-09-01" "2011-10-01" "2011-11-01" "2011-12-01"

I just needed the YYYY-MM format for this date as a character like this

 [1] "2011-01" "2011-02" "2011-03" "2011-04" "2011-05" "2011-061"
 [7] "2011-07" "2011-08" "2011-09" "2011-10" "2011-11" "2011-12"

What's the best way to code this in R? Thanks

aotearoa
  • 305
  • 1
  • 7
  • 19
  • Actually that one may not be a duplicate but then again this question too likely has one somewhere. – Dirk Eddelbuettel May 05 '17 at 14:53
  • @DirkEddelbuettel I interpreted the question as "I know how to increment dates with `seq`, but would like to extract the month piece". Under that interpretation the dupe @sotos pointed out seems reasonable. – BrodieG May 05 '17 at 14:59

1 Answers1

4

The key is to use proper types. Never ever use characters for dates.

R> p1 <- as.Date("2011-01-01")
R> p2 <- as.Date("2012-12-31")
R> mydates <- seq(p1, p2, by="day")
R> head(mydates)
[1] "2011-01-01" "2011-01-02" "2011-01-03" "2011-01-04" "2011-01-05" "2011-01-06"
R> str(mydates)
 Date[1:731], format: "2011-01-01" "2011-01-02" "2011-01-03" "2011-01-04" "2011-01-05" "2011-01-06" "2011-01-07" ...
R> 

For the proper types Date and POSIXct (for Datetime), R has a lot of useful computational infrastructure. As you see here, sequence creation "just works".

You can then do additional tricks like excluding weekends etc.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725