2012-03-13 153 views
0

我有一個主要的XTS對象「Data」,其中有〜1M行,跨越22天。我有另一個XTS對象「Set」,有22行,每天有1個條目。我想將這個較小的XTS對象組合到較大的對象中,這樣它就會有一個包含當天Set值的附加列。根據R中的另一個xts對象將列添加到xts對象

首先我想:

> Data=cbind(Data,as.numeric(Set[as.Date(index(Data[]))])) 
Error in error(x, ...) : 
improper length of one or more arguments to merge.xts 

然後我嘗試:

> Data=cbind(Data,1) 
> Data[,6]=as.numeric(Set[as.Date(index(Data[,6]))]) 
Error in NextMethod(.Generic) : 
    number of items to replace is not a multiple of replacement length 

我也試過沒有as.numeric但收到了同樣的錯誤。我試圖將數據轉化爲一個data.frame並得到了錯誤:

Error in `[<-.data.frame`(`*tmp*`, , 6, value = c(1, 397.16, 397.115, : 
    replacement has 22 rows, data has 835771 

什麼我做錯了,我怎麼做到這一點?過去兩週我只用過R。

謝謝!

> str(Data) 
An ‘xts’ object from 2012-01-03 05:01:05 to 2012-01-31 14:59:59 containing: 
    Data: num [1:835771, 1:5] 397 397 397 397 397 ... 
- attr(*, "dimnames")=List of 2 
    ..$ : NULL 
    ..$ : chr [1:5] "SYN" "\"WhitePack.BID_SIZE\"" "\"WhitePack.BID_PRICE\"" "\"WhitePack.ASK_PRICE\"" ... 
    Indexed by objects of class: [POSIXct,POSIXt] TZ: 
    xts Attributes: 
NULL 
> str(Set) 
An ‘xts’ object from 2012-01-02 to 2012-01-31 containing: 
    Data: chr [1:22, 1] " 1.000" "397.160" "397.115" "397.175" "397.200" "397.390" "397.560" "397.580" "397.715" ... 
- attr(*, "dimnames")=List of 2 
    ..$ : NULL 
    ..$ : chr "Settle" 
    Indexed by objects of class: [POSIXct,POSIXt] TZ: 
    xts Attributes: 
NULL 

回答

1

你獲得成功:

df3 <- merge(Data, Set) 

爲了解決我缺乏的原始問題有充分的瞭解,我認爲唯一的額外步驟是:

df3[, 6] <- na.locf(df3[, 6]) 
+0

不,這除了這22個數據單元外,每個新的數據單元中都會添加22行到數據,其中NA爲0. – user1266555 2012-03-13 13:43:01

+0

您需要發佈str(Data)和str(Set)的結果。我猜你的索引格式不符合你的想法。 – 2012-03-13 13:49:27

+0

我編輯了原始文章以包含此內容。 – user1266555 2012-03-13 13:53:30