为什么split在R中强制加倍为整数并且有解决方法

why does split coerce double to integer in R and is there a workaround

可以在 R 中从数字类型甚至小数值构建日期。这不是很常见,但例如在平均日期时会发生。不幸的是,它们似乎坏了 split

> as.Date(-1, origin = "1970-01-01")
[1] "1969-12-31"
> as.Date(-1.0001, origin = "1970-01-01")
[1] "1969-12-30"
> split(as.Date(-1, origin = "1970-01-01"), 1)[[1]]
[1] "1969-12-31"
> split(as.Date(-1.0001, origin = "1970-01-01"), 1)[[1]]
[1] "1969-12-31" #this is wrong
> unclass(split(as.Date(-1, origin = "1970-01-01"), 1)[[1]])
[1] -1
> unclass(split(as.Date(-1.0001, origin = "1970-01-01"), 1)[[1]])
[1] -1 #this is "why"

因此 split 使两个不同的日期相等。人们是否同意这是一个错误,还是我错过了深层原因?任何解决方法?谢谢

无论出于何种原因,split.DateDate 输入强制转换为整数:

> split.Date
function (x, f, drop = FALSE, ...) 
{
    y <- split.default(as.integer(x), f, drop = drop)
    for (i in seq_along(y)) class(y[[i]]) <- "Date"
    y
}
<bytecode: 0x2effb98>
<environment: namespace:base>

这至少是函数和文档之间的不恰当之处,因为 ?Date 说 "the date should be an integer, but this is not enforced in the internal representation."。有些人可能认为这是一个错误。我不确定。

您可以通过直接调用 split.default 来避免这种情况。

> split.default(as.Date(-1.0001, origin = "1970-01-01"), 1)[[1]]
[1] "1969-12-30"