xts 合并奇怪的行为 [英] xts merge odd behaviour

查看:23
本文介绍了xts 合并奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 3 个 xts 对象,它们的索引都是日期"对象:

I have 3 xts objects all of whose indicies are 'Date' objects:

    > 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

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

Now I'm seeing this odd behaviour:

    > 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

虽然以下合并工作正常:

While the following merge works fine:

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

我无法弄清楚这里可能发生了什么.有什么想法吗?

I can't figure out what could possibly be going on here. Any idea?

更新:

    > 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 重新计算日期解决了问题.

Indeed, the problem is that the indices are not identical (as verified by .index(a) == .index(b) ). Converting to numeric then recreating an xts and recomputing the dates with asDate fixed the problem.

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

This objects were created from the to.daily method from xts.

推荐答案

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

You can't use index() to verify the indices are the same because it converts the index to whatever is specified by indexClass(). Use .index to get the raw numeric index, then you will likely find that:

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

您应该调查您的数据源,看看是什么导致了这种情况.要快速修复,请执行以下操作:

You should investigate your data source to see what might be causing this. For a quick fix, do this:

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

这篇关于xts 合并奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆