1

What gives in this example? How come it does not generate what I expect it to, and how can I change that behaviour?

date_seq <- seq(ymd('2023-03-22'), ymd('2023-03-27'), as.difftime(days(1)))

[1] "2023-03-22" "2023-03-23" "2023-03-24" "2023-03-25" "2023-03-26" "2023-03-27"

Then I loop through it for(i in date_seq) print(i) and surprise, surprise:

...
[1] 19442
[1] 19443

No dates to be found!

You need to apparently use for (i in seq_along(date_seq)) print(date_seq[i]) and voila!

...
[1] "2023-03-26"
[1] "2023-03-27"
M--
  • 25,431
  • 8
  • 61
  • 93
  • I've not played with R, but this looks like a display/formatting issue. E.g. if you take the number `19442` put it in Excel and format it as a date, it displays `1953-03-24`; which seems close to your input (albeit 70 years out)... So I suspect R has some base date from which this number is an offset. – JohnLBevan Mar 29 '23 at 07:54
  • 1
    Powershell `(get-date).AddDays(-19442)` returns 4th Jan 1970, so I suspect R's base date is `1970-01-01`. Lots more info on "epoch" dates here: https://stackoverflow.com/a/26391999/361842 – JohnLBevan Mar 29 '23 at 07:55
  • 1
    @JohnLBevan Thanks! That made sense. R is still weird af.. I'm supplying it a Date vector and it gives back a numeric in the for-loop x___x – Petyo Zhechev Mar 29 '23 at 08:08

1 Answers1

2

Not sure why the for loop changes the dates to numeric values, but you can prevent it by providing the date vector as a list, which preserves the date class.

v <- seq(ymd('2023-03-22'), ymd('2023-03-27'), "day")

for(i in as.list(v)) print(i)

[1] "2023-03-22"
[1] "2023-03-23"
[1] "2023-03-24"
[1] "2023-03-25"
[1] "2023-03-26"
[1] "2023-03-27"
Merijn van Tilborg
  • 5,452
  • 1
  • 7
  • 22