简体   繁体   English

如何将zoo对象的数据列保存到矩阵?

[英]How to save data column of zoo object to matrix?

I am downloading some data using R package tseries, 我正在使用R包tseries下载一些数据,

require('tseries')
tickers<- c('JPM','AAPL','MSFT','FB','GE');
prices = matrix(NA,nrow=40,ncol=6)
startdate<-'2015-02-02'
enddate<-'2015-03-30'# 40 rows dim()
for(i in 1:5){
  prices[,i]<-get.hist.quote(
    instrument=tickers[i],
    start=startdate,
    end=enddate,
    quote='AdjClose',
    provider='yahoo')
}
colnames(prices)<-c('JPM','AAPL','MSFT','FB','GE');

I want to construct a matrix saving the adjclose price and date information, but I don't know how to access the zoo date column, say when I construct a zoo object using get.hist.quote(), I can view the object like this 我想构建一个保存adjclose价格和日期信息的矩阵,但我不知道如何访问动物园日期列,比如当我使用get.hist.quote()构建一个zoo对象时,我可以像查看对象一样这个

动物园对象

But when I save them to matrix, the date column is missing 但是当我将它们保存到矩阵时,缺少日期列 矩阵对象

Here Map applied to get.hist.quote will create a zoo object for each ticker. 这里Map应用get.hist.quote将为每个股票动物园对象。 Then we use zoo's multiway merge.zoo to merge them all together creating a final zoo object prices : 然后我们使用zoo的multiway merge.zoo将它们合并在一起,创建最终的zoo对象prices

prices <- do.call(merge, 
  Map(get.hist.quote, tickers,
    start=startdate,
    end=enddate,
    quote='AdjClose',
    provider='yahoo')
)

I would probably keep all the series in a zoo object. 我可能会将所有系列保存在zoo对象中。 This can be done like in the following code, thereby also avoiding your for-loop etc. You can always convert this object to a matrix by as.matrix() afterwards. 这可以像下面的代码一样完成,从而避免你的for循环等。之后你可以通过as.matrix()将这个对象转换为matrix

prices <-lapply(tickers, get.hist.quote, start=startdate, end=enddate, quote='AdjClose')
prices <- Reduce(cbind, prices)
names(prices) <- tickers
prices <- as.matrix(prices)
head(prices)
             JPM   AAPL  MSFT    FB    GE
2015-02-02 55.10 118.16 40.99 74.99 23.99
2015-02-03 56.35 118.18 41.31 75.40 24.25
2015-02-04 56.01 119.09 41.54 75.63 23.94
2015-02-05 56.40 119.94 42.15 75.61 24.28
2015-02-06 57.51 118.93 42.11 74.47 24.30
2015-02-09 57.44 119.72 42.06 74.44 24.42

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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