2011-10-06 109 views
3

我有3個XTS對象其所有indicies是「日期」對象: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方法創建的。

+0

請更換打印'A','B','C'的結果的結果(a)','dput(b)','dput(c)''。 –

+0

謝謝,它現在有效。 – functor

+0

我會考慮to.period。感謝您的背景。 –

回答

3

您不能使用index()來驗證索引是否相同,因爲它將索引轉換爲由indexClass()指定的任何索引。使用.index獲得的原始數字索引,那麼你可能會發現:

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

您應該研究您的數據源,看看有什麼可能會導致此。要快速修復,請執行以下操作:

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

當然這似乎令人費解,但原因是Date不準確。任何內的日曆日是相同的「日期」。

某個地方,正如喬什所說的,事實是您的數據是以不同的方式/來源創建的。我會試着想一個更好的方法來管理這種變化 - 因爲它不是一個純粹的新穎問題。在此之前:

index(x) <- index(x) 

將做的伎倆。爲什麼?

正如喬希所指出的,index(x) [no <-]採用底層的POSIX time_t表示法並將其轉換爲Date(自紀元以來的天數)。經由index<-替換原始索引中的 「日期」 迴轉換成POSIX時間(POSIXct在R,time_t在C)

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