【问题标题】:xts merge odd behaviourxts 合并奇怪的行为
【发布时间】:2011-10-06 17:20:24
【问题描述】:

我有 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 方法创建的。

【问题讨论】:

  • 请将打印abc的结果替换为dput(a)dput(b)dput(c)的结果。
  • 我会调查 to.period。谢谢你的背景。

标签: r xts


【解决方案1】:

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

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

index(x) <- index(x) 

会成功的。为什么?

正如 Josh 所说,index(x) [no &lt;- ] 采用底层 POSIX time_t 表示并将其转换为日期(自纪元以来的天数)。通过index&lt;- 替换原始索引会将“日期”转换回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

【讨论】:

    【解决方案2】:

    您不能使用index() 来验证索引是否相同,因为它将索引转换为indexClass() 指定的任何内容。使用.index 获取原始数字索引,您可能会发现:

    all(.index(a) == .index(b))  # is FALSE
    

    您应该调查您的数据源,看看可能是什么原因造成的。要快速修复,请执行以下操作:

    index(b) <- as.Date(index(b))
    

    【讨论】:

      猜你喜欢
      • 2019-12-22
      • 2023-03-16
      • 2019-12-13
      • 2017-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-17
      • 1970-01-01
      相关资源
      最近更新 更多