【问题标题】:Add two xts objects to a single data frame column将两个 xts 对象添加到单个数据框列
【发布时间】:2011-03-06 18:54:17
【问题描述】:

这是我想要达到的结果:

             Trade Time     Last  Yesterday Close
GLD 2011-03-04 04:00:00 139.3500           138.09  
SLV 2011-03-04 04:00:00  34.6925            33.42

要获取前两列,

require("quantmod")

intra <- getQuote("GLD;SLV", what=yahooQF("Last Trade (Price Only)")) 

>intra
             Trade Time     Last
GLD 2011-03-04 04:00:00 139.3500
SLV 2011-03-04 04:00:00  34.6925

> class(intra)
[1] "data.frame"

要获得昨天的收盘价,

require("quantmod")

getSymbols("GLD;SLV")

GLD <- GLD[,4]    #only the close
SLV <- SLV[,4]

GLD  <- head(tail(GLD, n=2), n=1)   #only yesterday
SLV  <- head(tail(SLV, n=2), n=1)

GLD  <- as.vector(GLD)  #prepare for merge with intra data.frame
SLV  <- as.vector(SLV)

EOD <- rbind(GLD, SLV)

> EOD
      [,1]
GLD 138.09
SLV  33.42

> class(EOD)
[1] "matrix"

然后,朴素的 merge() 方法

> super <- merge(intra, EOD)

> class(super)
[1] "data.frame"

> super
           Trade Time     Last   [,1]
1 2011-03-04 04:00:00 139.3500 138.09
2 2011-03-04 04:00:00  34.6925 138.09
3 2011-03-04 04:00:00 139.3500  33.42
4 2011-03-04 04:00:00  34.6925  33.42

关闭,但出现了严重错误。首先,我丢失了内部 data.frame 上的描述性 GLD 和 SLV 标签。其次,我有四行而不是两行(神秘的重复)。

重构技巧总是受欢迎的。

【问题讨论】:

    标签: r dataframe xts


    【解决方案1】:

    这是你的意思吗?

    intra$YesterdayClose <- EOD
    intra
                 Trade.Time     Last YesterdayClose
    GLD 2011-03-04 04:00:00 139.3500         138.09
    SLV 2011-03-04 04:00:00  34.6925          33.42
    

    这假定EOD 中的顺序与数据框中的顺序相同,如果不是这种情况,那么您可以这样做:

    intra$YesterdayClose <- EOD[match(rownames(EOD),rownames(intra))]
    

    【讨论】:

    • 最棒的!谢谢。 (有点尴尬,答案就是这么简单,但我会克服的)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    相关资源
    最近更新 更多