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

Asked

Viewed 50 times

3

Can anyone explain why in for-loop the objects Date are converted to integer? In the code below I want to iterate on the 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 it doesn’t 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?

1 answer

3


(Adaptation of Soen’s response here)

The help page (?`for`) says the following:

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

As objects of the class Date are not vectors, are converted into a:

> 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 of using as.list() for as.vector() (which should be analogous to that used internally in the for) is that the first keeps the class Date of the elements (for a list can be heterogeneous and contain anything), and the second makes the conversion 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 the size of the date object and 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"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.