Why does the for-loop convert from Date to integer?

3

Does anyone know how to explain why for-loop objects are Date converted to integer ? In the code below I want to iterate in dates but these are converted to integers.

> dates <- Sys.Date() + 1:10
> dates
 [1] "2015-09-29" "2015-09-30" "2015-10-01" "2015-10-02" "2015-10-03" "2015-10-04" "2015-10-05" "2015-10-06" "2015-10-07" "2015-10-08"
> for (date in dates) print(date)
[1] 16707
[1] 16708
[1] 16709
[1] 16710
[1] 16711
[1] 16712
[1] 16713
[1] 16714
[1] 16715
[1] 16716

If I use a list this does not happen.

> for (date in as.list(dates)) print(date)
[1] "2015-09-29"
[1] "2015-09-30"
[1] "2015-10-01"
[1] "2015-10-02"
[1] "2015-10-03"
[1] "2015-10-04"
[1] "2015-10-05"
[1] "2015-10-06"
[1] "2015-10-07"
[1] "2015-10-08"

Does anyone know why?

    
asked by anonymous 29.09.2015 / 03:25

1 answer

2

(Adapting the SOen response here )

The help page ( ?'for' ) reads as follows:

  

An expression evaluating a vector (including a list and an expression) or a pairlist or NULL.

As objects of class Date are not vectors, they are converted into one:

> is.vector(Sys.Date())
[1] FALSE
> is.vector(as.numeric(Sys.Date()))
[1] TRUE

When you use a list, you transform the object into a vector (lists are vectors):

> is.vector(as.list(dates))
[1] TRUE

The difference from using as.list() to as.vector() (which should be analogous to that used internally in for ) is that the first holds the Date class of elements (since a list can be heterogeneous and contain anything ), and the second converts to numeric .

> sapply(as.list(dates), class)
[1] "Date" "Date" "Date" "Date" "Date" "Date" "Date" "Date" "Date" "Date"

Another relatively simple alternative is to loop in a sequence of the date object's size and make the subset:

> for (date in seq_along(dates)) print(dates[date])
[1] "2015-09-29"
[1] "2015-09-30"
[1] "2015-10-01"
[1] "2015-10-02"
[1] "2015-10-03"
[1] "2015-10-04"
[1] "2015-10-05"
[1] "2015-10-06"
[1] "2015-10-07"
[1] "2015-10-08"
    
29.09.2015 / 04:09