r - xts 合并奇怪的行为

标签 r xts

我有 3 个 xts 对象,它们的标记都是“日期”对象:

    > a
                  a
    1995-01-03 1.76
    1995-01-04 1.69
    > b
                  b
    1995-01-03 1.67
    1995-01-04 1.63
    > c
                   c
    1995-01-03 1.795
    1995-01-04 1.690

验证索引是否相同:

    > index(a) == index(b)
    [1] TRUE TRUE
    > index(a) == index(c)
    [1] TRUE TRUE

现在我看到了这种奇怪的行为:

    > merge.xts(a,b)
                  a    b
    1995-01-03   NA 1.67
    1995-01-03 1.76   NA
    1995-01-04   NA 1.63
    1995-01-04 1.69   NA

虽然以下合并工作正常:

    > merge.xts(a,c)
                  a     c
    1995-01-03 1.76 1.795
    1995-01-04 1.69 1.690

我不知道这里可能发生了什么。有什么想法吗?

更新:

    > dput(a)
    structure(c(1.76, 1.69), .indexCLASS = "Date", .indexTZ = "", .CLASS = "xts", class = c("xts", 
    "zoo"), index = structure(c(789168240, 789254580), tzone = "", tclass = "Date"), .Dim = c(2L, 
    1L), .Dimnames = list(NULL, "a"))

    > dput(b)
    structure(c(1.67, 1.63), .indexCLASS = "Date", .indexTZ = "", .CLASS = "xts", class = c("xts", 
    "zoo"), index = c(789109200, 789195600), .Dim = c(2L, 1L), .Dimnames = list(
        NULL, "b"))

    > dput(c)
    structure(c(1.795, 1.69), .indexCLASS = "Date", .indexTZ = "", .CLASS = "xts", class = c("xts", 
    "zoo"), index = c(789109200, 789195600), .Dim = c(2L, 1L), .Dimnames = list(
        NULL, "c"))

确实,问题在于索引不相同(由 .index(a) == .index(b) 验证)。转换为数字然后重新创建 xts 并使用 asDate 重新计算日期解决了这个问题。

这个对象是从 xts 的 to.daily 方法创建的。

最佳答案

当然这看起来很复杂,但原因是 Date 不精确。一个日历日的任何时间都是相同的“日期”。

正如 Josh 所暗示的,在某个地方,您的数据是以不同的方式/来源创建的。我会尝试想出一种更好的方法来管理这种可变性——因为它不是一个纯粹的新问题。到那时:

index(x) <- index(x) 

会成功的。为什么?

正如乔希所说,index(x) [没有<- ] 采用底层 POSIX time_t表示并将其转换为日期(自纪元以来的天数)。通过 index<- 替换原始索引将“日期”转换回 POSIX 时间(R 中的 POSIXct,C 中的 time_t)

 t1 <- Sys.time()
 t2 <- Sys.time()

 as.Date(t1) == as.Date(t2)
 #[1] TRUE

 t1 == t2
 #[1] FALSE


 x1 <- xts(1, t1)
 x2 <- xts(2, t2)


 indexClass(x1) <- "Date"
 indexClass(x2) <- "Date"
 cbind(x1,x2)
            ..1 ..2
 2011-10-06   1  NA
 2011-10-06  NA   2

 .index(cbind(x1,x2))
 [1] 1317925443 1317925447
 attr(,"tzone")
 [1] "America/Chicago"
 attr(,"tclass")
 [1] "Date"

 # ugly, ugly solution
 index(x1) <- index(x1)
 index(x2) <- index(x2)
 cbind(x1,x2)
            ..1 ..2
 2011-10-06   1   2
 .index(cbind(x1,x2))
 [1] 1317877200

关于r - xts 合并奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7678090/

相关文章:

r - 在 R 中按名称和日期添加唯一 ID

r - 过滤至少具有两个特定值的行

r - 使用 Rcpp 找不到消息错误 'C:/Program'

R xts - 将不等时间步长 xts 重新采样为等距时间序列

r - 在 R 中对宽范围的动物园对象快速应用 xts 向量操作

r - 使用 R 的 dygraph 仅按年份绘制 xts 时间序列?

xts 对象列表中的 rbind.xts

r - 使用 xts 标准化股票图表

r - RMarkdown 中的 LaTeX 封装

r - R中的函数acf计算自相关