简体   繁体   中英

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)

This code is from TimelyPortfolio blog. It gives me error on the last line of runCor. The reason is that the number of observations of US10yRate is different from that of GSPC. US10yRate has non-contiguous dates (1990-01-02, 1990-01-05 etc.). I want to subset GSPC based on US10yRate dates, so that they can match with each other. This operation is exactly like merge in SQL. How can I deal with this with xts objects in R?

Thanks!

Take a look at GSPC , specifically it's number of rows.

> 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

You can merge them first to make sure they both have the same number of rows.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM