0

The class() of all elements I've encountered in R have been of length 1.

Some examples

library(dplyr)

"string" %>% class %>% length
# [1] 1

123 %>% class %>% length
# [1] 1

0.234 %>% class %>% length
# [1] 1

Sys.Date() %>% class %>% length
# [1] 1

But the class() of Sys.time() (which is itself, like the examples above, length 1) is length 2

Sys.time() %>% class %>% length
# [1] 2

Why?

stevec
  • 41,291
  • 27
  • 223
  • 311
  • Albeit a different class, a `data.table` has 2 classes, the answer from here might help to explain why: https://stackoverflow.com/a/15986236/2449656 – Khaynes Jan 20 '19 at 07:11
  • 1
    Also, see 13.6 from here: https://adv-r.hadley.nz/s3.html – Khaynes Jan 20 '19 at 07:16

1 Answers1

2

https://stat.ethz.ch/R-manual/R-devel/library/base/html/class.html is worth a read

But in essence the ability for objects to have multiple classes allows their behavior to change in certain situations, as the order of the class vector determines the order in which methods are searched.

In the case you've observed simple objects tend to have a singular class.

Sys.time() returns a timestamp which is a bit more complex, various methods are implemented for the classes and these can differ. Therefore if one were to try the object in a context where a method exists in the second class only, it would use the second classes method.

To view the methods, try the following:

methods(class = "POSIXt")
methods(class = "POSIXct")
zacdav
  • 4,603
  • 2
  • 16
  • 37
  • When an object has multiple classes, is there a rule for the order in which they're returned? The quick work around for what I'm doing presently might be to simply take the first result – stevec Jan 20 '19 at 21:21