本文介绍了将 getSymbols 结果合并到一个 xts 对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
library(quantmod)
tckrs <- c("TLT", "LQD", "HYG", "SPY", "DBC")
NumTckrs <- length(tckrs)
getSymbols(tckrs, from="1900-01-01", to=Sys.Date())
# merge to allign the start dates
MainDF <- merge(Ad(TLT), Ad(LQD), Ad(HYG), Ad(SPY), Ad(DBC), all=FALSE)
我不想在最后一行重复股票代码.有谁知道如何做到这一点?
I would like to not have to repeat the stock symbols in the last line. Does anyone know how this could be done?
推荐答案
将所有数据加载到一个环境中,然后对每个数据调用 Ad
并合并它们.另请注意,getSymbols
默认返回一个 xts 对象,因此您的 MainDF
是一个 xts 对象,而不是 data.frame.
Load all the data into an environment, then call Ad
on each, and merge them. Also note that getSymbols
returns an xts object by default, therefore your MainDF
is an xts object, not a data.frame.
library(quantmod)
# create new environment
myEnv <- new.env()
# pull all data and load into myEnv
getSymbols("TLT;LQD;HYG;SPY;DBC", env=myEnv)
# eapply calls Ad on each symbol in myEnv and returns a list
# do.call calls merge with each element returned from eapply as an argument
MainXTS <- do.call(merge, c(eapply(myEnv, Ad),all=FALSE))
这篇关于将 getSymbols 结果合并到一个 xts 对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!