Skip to content
Prev 50835 / 63421 Next

Weird issue when iterating through dates

On Wed, Aug 12, 2015 at 10:55 AM, G?bor Cs?rdi <csardi.gabor at gmail.com> wrote:
I would argue that this isn't a bug, not even in the documentation of
"for" (even though it might be clearer).  ?"for" says that `seq` is
"[A]n expression evaluating to a vector (including a list and an
expression) or to a pairlist or 'NULL'".  Date objects aren't strictly
vectors, so they're treated as integer/numeric.

This answer on StackOverflow said that "for" does not copy any of the
iterators attributes (including class), which causes this behavior.
http://stackoverflow.com/a/23278464/271616

To respond to the original question regarding why the code below,
"prints the dates as a string".  Quite simply, you convert seq(d1,d2,
by=1) to character, so it's no longer a Date.  The fact that
Sys.Date() and as.character(Sys.Date()) both *print* the same thing
does not mean they are the same.

for ( dt in as.character(seq(d1,d2, by=1)) ) {
  print(dt)
}

Best,
Josh