3

When using R's primitive c function, combining the current datetime with NULL gives:

> class(c(NULL,Sys.time()))
[1] "numeric"

But when passing NULL last:

> class(c(Sys.time(),NULL))
[1] "POSIXct" "POSIXt"

Is this intended? The documentation for c reads: "The output type is determined from the highest type of the components in the hierarchy NULL < raw < logical < integer < double < complex < character < list < expression." but there is no mention of order being relevant.

Is there a better (more consistent) way to combine objects of class POSIXct with NULL into a vector? Or should one always explicitly test for NULL and handle it as a seperate case?

ddisk
  • 310
  • 2
  • 7

1 Answers1

2

This is because c acts as an S3 generic, and there is a POSIXct method for it:

> c.POSIXct
function (..., recursive = FALSE) 
.POSIXct(c(unlist(lapply(list(...), unclass))))
<bytecode: 0x000001ab3e6efe58>
<environment: namespace:base>

(S3 methods dispatch on the class of the first argument, so c(POSIXct, NULL) will call c.POSIXct, whereas c(NULL, POSIXct) will call the default method.)

Hong Ooi
  • 56,353
  • 13
  • 134
  • 187