[Rd] Weird issue when iterating through dates
Gábor Csárdi
csardi.gabor at gmail.com
Thu Aug 6 10:10:48 CEST 2015
Date has a `[.Date` method and also `[[.Date`, but it looks like a for
loop does not consider the class of the object you are iterating over,
so these are ignored and the internal representation is used.
I think this is a bug, at least in the documentation of ?"for".
Interestingly, lapply and co. do consider the class:
invisible(lapply(seq(d1, d2, by = 1), print))
works as you would expect. (The invisible() is to suppress printing
the return value.)
Gabor
On Thu, Aug 6, 2015 at 3:24 AM, Luca Cerone <luca.cerone at gmail.com> wrote:
> Dear all,
> I am experiencing a weird issue when iterating through dates in R
> (3.1.2 and 3.2.1 on 64bit linux machines)
>
> I am bit surprised about the behaviour of this snippet of code:
>
> d1 <- as.Date('2015-01-01')
> d2 <- as.Date('2015-01-31')
>
> for ( dt in seq(d1,d2, by=1) ) {
> dt <- as.character(dt)
> print(dt)
> }
>
> for ( dt in as.character(seq(d1,d2, by=1)) ) {
> print(dt)
> }
>
> I can't find a good explanation why the first for loop would convert
> to string the numeric interpretation
> of the dates while the second one correctly (at least in my
> intentions) prints the dates as string.
>
> I am sure that it is not a bug in R but I would like to understand why
> I am getting different outputs from the two for loops.
>
> Thanks a lot in advance for your help!
>
> Cheers,
> Luca
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
More information about the R-devel
mailing list