簡體   English   中英

如何使用xts對象的索引來子集另一個xts對象?

[英]How to use the index of an xts object to subset another xts object?

require(quantmod)
require(TTR)
require(PerformanceAnalytics)

tckr<-"^GSPC"

start<-"1986-12-31"
end<- format(Sys.Date(),"%Y-%m-%d") # yyyy-mm-dd

getSymbols(tckr, from=start, to=end)
US10yRate<-getSymbols("DGS10",src="FRED",auto.assign=FALSE,from=start, to=end)

US10yRate<-to.daily(US10yRate)[,1]

#running 25 day correlation 
correlationSPand10y<-runCor(US10yRate[,1],GSPC[1:12789,2],n=25)

此代碼來自TimelyPortfolio博客。 它在runCor的最后一行給了我錯誤。 原因是US10yRate的觀察次數與GSPC的觀察次數不同。 US10yRate具有不連續的日期(1990年1月2日,1990年1月5日等)。 我想根據US10yRate日期對GSPC進行子集化,以便它們可以相互匹配。 此操作與SQL中的合並完全相同。 如何處理R中的xts對象?

謝謝!

看一下GSPC ,特別是行數。

> dim(GSPC)
[1] 6612    6

> GSPC[1:12789,2]
Error in `[.xts`(GSPC, 1:12789, 2) : subscript out of bounds

 U <- US10yRate[index(US10yRate) %in% index(GSPC),1]
 G <- GSPC[index(GSPC) %in% index(US10yRate), 2]
 dim(U)
 #  [1] 6552    1
 dim(G)
 #  [1] 6552    1

您可以先合並它們,以確保它們具有相同的行數。

dat <- merge(US10yRate[, 1], GSPC[, 2], all=FALSE)
# or,
# dat <- na.locf(merge(US10yRate[, 1], GSPC[, 2]))

correlationSPand10y <- runCor(dat[, 1], dat[, 2], n=25)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM