【问题标题】:Adding column to xts object based on another xts object in R基于R中的另一个xts对象将列添加到xts对象
【发布时间】:2012-03-13 13:30:42
【问题描述】:

我有一个主要的 XTS 对象“数据”,其中大约 100 万行跨越 22 天。我有另一个 XTS 对象“Set”,有 22 行,每天 1 个条目。我想将这个较小的 XTS 对象合并到较大的 XTS 对象中,这样它就会有一个额外的列,其中包含当天在 Set 中的值。

首先我尝试过:

> 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 转换为 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

【问题讨论】:

    标签: r xts


    【解决方案1】:

    你成功了吗:

    df3 <- merge(Data, Set)
    

    为了解决我对原始问题缺乏充分理解,我认为唯一的额外步骤是:

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

    【讨论】:

    • 不,这会在除这 22 行之外的每个新数据单元格中向 Data 中添加 22 行。
    • 你需要发布str(Data)和str(Set)的结果。我猜你的索引格式不是你想象的那样。
    • 您不需要拨打coredata。如果Set 中的22 个索引值与Data 中的略有不同,您可以通过:df3 &lt;- df3[index(Data),] 删除它们。
    • 经过几个错误的步骤后,我认为上述附录应该成功。您可能不需要删除插入隐式午夜时间的额外 22 行。
    • > df3$Settle=na.locf(df$Settle) df[, 6] 中的错误:'closure' 类型的对象不是子集 > df4=as.data.frame(df3) > df4$settle=na.locf(df4$settle) > df3=as.xts(df4) 这行得通。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 2016-01-07
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多