Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: What are dates in a dates vector: dates or numeric values? (difference between x[i] and i)

Tags:

date

r

Could anyone explain please why in the first loop each element of my dates vector is a date while in the second each element of my dates vector is numeric? Thank you!

x <- as.Date(c("2018-01-01", "2018-01-02", "2018-01-02", "2018-05-06"))
class(x)
# Loop 1 - each element is a Date:
for (i in seq_along(x)) print(class(x[i]))
# Loop 2 - each element is numeric:
for (i in x) print(class(i))             
like image 861
user3245256 Avatar asked May 17 '19 20:05

user3245256


1 Answers

The elements are Date, the first loop is correct.

Unfortunately R does not consistently have the style of the second loop. I believe that the issue is that the for (i in x) syntax bypasses the Date methods for accessors like [, which it can do because S3 classes in R are very thin and don't prevent you from not using their intended interfaces. This can be confusing because something like for (i in 1:4) print(i) works directly, since numeric is a base vector type. Date is S3, so it is coerced to numeric. To see the numeric objects that are printing in the second loop, you can run this:

x <- as.Date(c("2018-01-01", "2018-01-02", "2018-01-02", "2018-05-06"))
for (i in x) print(i)
#> [1] 17532
#> [1] 17533
#> [1] 17533
#> [1] 17657

which is giving you the same thing as the unclassed version of the Date vector. These numbers are the days since the beginning of Unix time, which you can also see below if you convert them back to Date with that origin.

unclass(x)
#> [1] 17532 17533 17533 17657
as.Date(unclass(x), "1970-01-01")
#> [1] "2018-01-01" "2018-01-02" "2018-01-02" "2018-05-06"

So I would stick to using the proper accessors for any S3 vector types as you do in the first loop.

like image 145
Calum You Avatar answered Sep 19 '22 14:09

Calum You