[R] Unexpected behavior looping through sequence of dates

Peter Ehlers ehlers at ucalgary.ca
Sat Mar 9 21:23:11 CET 2013


On 2013-03-09 11:14, R. Michael Weylandt wrote:
> On Sat, Mar 9, 2013 at 6:50 PM, David Winsemius <dwinsemius at comcast.net> wrote:
>> I was unable to find the reason for the original coercion in the help("for") page or the R
>> Language Definition entry regarding for-loops. On the hunch that coercion via as.vector
>> might be occurring,
>
> Behaviorally, it seems to, but the code for do_for in eval.c has
> factors special-cased to call
> asCharacterFactor so that might not be a robust detail to rely on. The
> relevant behavior seems instead to be that there's a
> switch on val_type which creates the loop index but doesn't copy all
> attributes (like class)
>
> Note that this means a user's as.vector wouldn't be called here:
>
> as.vector.flub <- function(x, ...) letters[x]
>
> foo <- 1:5
> class(foo) <- "flub"
>
> as.vector(foo)
>
> for(j in foo) {print(j); print(class(j))}
>
> as.vector.grub <- function(x, ...) match(x, letters)
>
> bar <- letters[1:5]
> class(bar) <- "grub"
>
> as.vector(bar)
>
> for(j in bar) {print(j); print(class(j))}
>
> Cheers,
> Michael

I think that Michael is right - the problem is with val_type
in the do_for code.

Here's a simplified version of Alexandre's example:

  d <- as.Date("2013-03-10")
  for(i in seq_along(d)) print(i)
  #[1] 1

  for(i in d) print(i)
  #[1] 15774
where we might have expected to see "2013-03-10".

The essential line in the do_for code seems to me to be:

  val_type = TYPEOF(val);

?typeof tells us that R does not have a 'date' type, so:

  typeof(d)
  #[1] "double"

And the for-loop results follow.

Peter Ehlers



More information about the R-help mailing list