Reputation: 73
As I understand when the objects being concatenated with the c(...) function are of different types they are coerced into a single type which is the type of the output object
According the the R documentation
The output type is determined from the highest type of the components in the hierarchy NULL < raw < logical < integer < double < complex < character < list < expression.
Dates have a data type of double so if paired with a character should result in a character, if paired with an integer should result in a double, as we can see here
> a<-as.Date("2019-01-01")
> c("a",a)
[1] "a" "17901"
> c(1L,a)
[1] 1 17901
> typeof(c(1L,a))
[1] "double"
However if the date is first the function tries to convert the other values to class Date. This does not seem to match the behaviour from the documentation
> c(a,1)
[1] "2019-01-05" "1970-01-02"
> c(a,"a")
[1] "2019-01-05" NA
Warning message: In as.POSIXlt.Date(x) : NAs introduced by coercion
What additional rules are being applied here? Or alternatively what have I misunderstood about the situation?
Upvotes: 6
Views: 128
Reputation: 206411
Functions can be "overloaded" in R based on the data type of the first parameter. You can see there is a special c.Date
function that is run when you call c
with Date
object as the first parameter. You can see all the "special" c()
functions with methods("c")
. These functions can (and do) define different rules than the base c()
function. But since overloading only happens based on the data type of the first parameter, the order in which the values appear makes a big difference.
Upvotes: 4