0

I'm trying to run the following code in R

> mySeq <-  seq(as.Date("2012-1-1",format = "%Y-%m-%d"),
          as.Date("2012-1-3",format = "%Y-%m-%d"),
          by="1 day")

> for (i in mySeq){print(i)}

And I get:

[1] 15340
[1] 15341
[1] 15342

but mySeq[1] returns "2012-01-01"

Why? what am I missing here?

Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
Ika
  • 1,456
  • 1
  • 15
  • 24
  • 1
    if you add `as.Date(i)` will give you what you want. `for (i in mySeq){print(as.Date(i))}` – Jilber Urbina Apr 22 '13 at 13:05
  • Actually your solution did not work for me. I get: for (i in mySeq){print(as.Date(i))} Error in as.Date.numeric(i) : 'origin' must be supplied" – Ika Apr 22 '13 at 13:12

1 Answers1

4

Your date values are converted to numeric in for() function to use them as index values.

Instead you can use seq_along() to get index values and then print mySeq[i].

for(i in seq_along(mySeq)) {print(mySeq[i])}
Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201