Print a date range in a loop with correctly formatted dates [duplicate]

Typing this into the console gives:

seq(as.Date('2020-04-02'), as.Date('2020-04-30'), by = 'day')
 [1] "2020-04-02" "2020-04-03" "2020-04-04" "2020-04-05" "2020-04-06" "2020-04-07" "2020-04-08" "2020-04-09" "2020-04-10" "2020-04-11" "2020-04-12"
[12] "2020-04-13" "2020-04-14" "2020-04-15" "2020-04-16" "2020-04-17" "2020-04-18" "2020-04-19" "2020-04-20" "2020-04-21" "2020-04-22" "2020-04-23"
[23] "2020-04-24" "2020-04-25" "2020-04-26" "2020-04-27" "2020-04-28" "2020-04-29" "2020-04-30"

My loop:

for(i in seq(as.Date('2020-04-02'), as.Date('2020-04-30'), by = 'day')) {print(i)}

Gives:

[1] 18354
[1] 18355
[1] 18356
[1] 18357
[1] 18358
[1] 18359
[1] 18360
[1] 18361
[1] 18362
[1] 18363
[1] 18364
[1] 18365
[1] 18366
[1] 18367
[1] 18368
[1] 18369
[1] 18370
[1] 18371
[1] 18372
[1] 18373
[1] 18374
[1] 18375
[1] 18376
[1] 18377
[1] 18378
[1] 18379
[1] 18380
[1] 18381
[1] 18382

Expected actual dates.

Tried:

print(as.Date(i))

But this gives:

Error in as.Date.numeric(i) : 'origin' must be supplied

How can I print my date range via a loop?


Solution 1:

Try:

for (i in as.list(seq(as.Date('2020-04-02'), as.Date('2020-04-30'), by = 'day'))) {
  print(i)
}

I don't know why this is necessary, but if you run

for (i in Sys.Date()) {browser();print(i);}
# Called from: top level 
# Browse[1]> 
debug at #1: print(i)
# Browse[1]> 
i
# [1] 18709

you'll see that i is being converted to numeric in the for (.) portion. The as.list helps preserve that class.

Solution 2:

Another way is to supply the origin argument to as.Date:

for(i in seq(as.Date('2020-04-02'), as.Date('2020-04-30'), by = 'day')){
  print(as.Date(i, origin="1970-01-01"))}

When R transforms a date into a numeric, it returns the number of days after 197-01-01. Other softwares use different origins.