R - 将数据帧转换为时间序列

Aja*_*jay 13 r time-series

我有谷歌股票数据.它有两列Date(每日数据)和Close,即谷歌收盘指数.

Date    Close
10/11/2013  871.99
10/10/2013   868.24
10/9/2013    855.86
10/8/2013   853.67
10/7/2013   865.74
10/4/2013   872.35
10/3/2013   876.09
10/2/2013   887.99
10/1/2013   887
9/30/2013   875.91
9/27/2013   876.39
9/26/2013   878.17
9/25/2013   877.23
9/24/2013   886.84
Run Code Online (Sandbox Code Playgroud)

它以csv格式,我通过read.csv读取它返回数据框对象.当我尝试将其转换为timeseries/ts()对象时,它会返回不需要的数字.

请帮我将数据帧转换为ts()对象.

提前致谢.

Chi*_*til 14

我建议使用xts而不是ts因为它具有很多功能,特别是对于金融时间序列.如果您的数据位于data.frame中,DF则可以将其转换xts为如下所示

xts(DF$Close, as.Date(DF$Date, format='%m/%d/%Y')
Run Code Online (Sandbox Code Playgroud)

  • 好的,你建议......但为什么呢?是什么让xts比ts更好? (3认同)

Jil*_*ina 5

这是一种使用zoozoo包然后强制结果的方法ts

> library(zoo)
> ZOO <- zoo(df$Close, order.by=as.Date(as.character(df$Date), format='%m/%d/%Y'))
> ZOO
2013-09-24 2013-09-25 2013-09-26 2013-09-27 2013-09-30 2013-10-01 2013-10-02 2013-10-03 2013-10-04 
    886.84     877.23     878.17     876.39     875.91     887.00     887.99     876.09     872.35 
2013-10-07 2013-10-08 2013-10-09 2013-10-10 2013-10-11 
    865.74     853.67     855.86     868.24     871.99 
> ts(ZOO)  # coercing to be `ts`
Time Series:
Start = 1 
End = 14 
Frequency = 1 
 [1] 886.84 877.23 878.17 876.39 875.91 887.00 887.99 876.09 872.35 865.74 853.67 855.86 868.24
[14] 871.99
attr(,"index")
 [1] "2013-09-24" "2013-09-25" "2013-09-26" "2013-09-27" "2013-09-30" "2013-10-01" "2013-10-02"
 [8] "2013-10-03" "2013-10-04" "2013-10-07" "2013-10-08" "2013-10-09" "2013-10-10" "2013-10-11"
Run Code Online (Sandbox Code Playgroud)