2012-03-13 131 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