使用 c() 函数强制日期涉及的规则是什么

What are the rules involved in coercing dates with the c() function

据我了解,当与 c(...) 函数连接的对象属于不同类型时,它们会被强制转换为单一类型,即输出对象的类型

根据 R 文档

The output type is determined from the highest type of the components in the hierarchy NULL < raw < logical < integer < double < complex < character < list < expression.

日期的数据类型为双精度,因此如果与字符配对应生成字符,如果与整数配对应生成双精度,正如我们在此处看到的那样

> a<-as.Date("2019-01-01")
> c("a",a)
[1] "a"     "17901"
> c(1L,a)
[1]     1 17901
> typeof(c(1L,a))
[1] "double"

但是,如果日期是第一个,函数会尝试将其他值转换为 class 日期。这似乎与文档中的行为不符

> 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

此处应用了哪些附加规则?或者我对这种情况有什么误解?

根据第一个参数的数据类型,R 中的函数可以是 "overloaded"。当你以 Date 对象作为第一个参数调用 c 时,你可以看到有一个特殊的 c.Date 函数是 运行。您可以使用 methods("c") 查看所有 "special" c() 函数。这些函数可以(并且确实)定义了与基础 c() 函数不同的规则。但是由于重载只根据第一个参数的数据类型发生,所以值出现的顺序有很大的不同。