2

I want to loop over a series of dates in R. Here's some sample code:

myDates <- seq.Date(as.Date("2020-01-01"), as.Date("2020-01-03"), by = "day")
myDates[1]
class(myDates[1])

This creates a vector of dates, and I confirm this by printing and checking the class of the first element.

However, when I run this loop:

for (myDate in myDates) print(myDate)

I get this output:

[1] 18262
[1] 18263
[1] 18264

Having checked out this question I've got some workarounds to solve my immediate issue, but can anyone explain to me why this happens, and if there's a simple way to iterate directly over a vector of dates?

Tom Wagstaff
  • 1,443
  • 2
  • 13
  • 15
  • Can you tell what your ultimate goal is? – markus Mar 25 '20 at 22:29
  • 3
    While I agree, that is puzzling (as some things in R *are*), you can do `for (myDate in as.list(myDates)) print(myDate)` and it works as you might expect. (There are several times in R that a vector is un-classes, including `ifelse` and similar. This is apparently one of those cases.) – r2evans Mar 25 '20 at 22:37
  • 1
    Another reference : https://stackoverflow.com/questions/59572195/how-to-display-real-dates-in-a-loop-in-r/ – Ronak Shah Mar 26 '20 at 02:04

1 Answers1

0

The reason has been explained by @r2evans in the comments of your post. Actually you have a couple of methods to circumvent the issue, e.g.,

> d <- Map(print,myDates)
[1] "2020-01-01"
[1] "2020-01-02"
[1] "2020-01-03"

or

> for (myDate in as.character(myDates)) print(myDate)
[1] "2020-01-01"
[1] "2020-01-02"
[1] "2020-01-03"
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
  • Thanks @ThomasIsCoding, I think the top method is similar to r2evans suggestion to coerce it to a list. The second one actually doesn't suit my case because I do need to preserve the date type within the loop... – Tom Wagstaff Mar 26 '20 at 09:59