Loop over dates in R

Viewed 920

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?

1 Answers

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"
Related