将Zoo转换为数据框 [英] converting zoo to dataframe

查看:167
本文介绍了将Zoo转换为数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 zoo时间序列转换为 R 的数据框,并且日期成为数据的索引帧。有没有一种方法可以将日期表示为数据框中的普通列?

I converted a zoo time series into a data frame in R and the date became the index of the data frame. Is there a way to have the date represented as a normal column in the data frame?

monthly_df <- data.frame(monthly_zoo)

head(monthly_zoo)

head(monthly_df)

推荐答案

您要 as.data.frame()。证人:

R> library(quantmod)
Loading required package: xts
Loading required package: TTR
Version 0.4-0 included new data defaults. See ?getSymbols.
R> IBM <- as.zoo(getSymbols("IBM"))  # convert from xts
R> class(IBM)
[1] "zoo"
R> tail(IBM)
           IBM.Open IBM.High IBM.Low IBM.Close IBM.Volume IBM.Adjusted
2016-10-11   156.73   156.95  153.89    154.79    2901300       154.79
2016-10-12   154.97   154.97  153.08    154.29    2964000       154.29
2016-10-13   153.70   154.22  152.27    153.72    2909900       153.72
2016-10-14   154.47   155.53  154.09    154.45    4358200       154.45
2016-10-17   154.45   155.89  154.34    154.77    5890400       154.77
2016-10-18   150.02   151.00  147.79    150.72   12705700       150.72
R> as.data.frame(tail(IBM))
           IBM.Open IBM.High IBM.Low IBM.Close IBM.Volume IBM.Adjusted
2016-10-11   156.73   156.95  153.89    154.79    2901300       154.79
2016-10-12   154.97   154.97  153.08    154.29    2964000       154.29
2016-10-13   153.70   154.22  152.27    153.72    2909900       153.72
2016-10-14   154.47   155.53  154.09    154.45    4358200       154.45
2016-10-17   154.45   155.89  154.34    154.77    5890400       154.77
2016-10-18   150.02   151.00  147.79    150.72   12705700       150.72
R> class(as.data.frame(tail(IBM)))
[1] "data.frame"
R> 

要将日期添加为列(而不是依赖默认的行名),请使其明确:

To add the date as a column (instead of relying on the default rownames) make it explicit:

R> IBM <- getSymbols("IBM")  # keep as xts
R> tail(data.frame(index(IBM), as.data.frame(IBM)))
           index.IBM. IBM.Open IBM.High IBM.Low IBM.Close IBM.Volume IBM.Adjusted
2016-10-11 2016-10-11   156.73   156.95  153.89    154.79    2901300       154.79
2016-10-12 2016-10-12   154.97   154.97  153.08    154.29    2964000       154.29
2016-10-13 2016-10-13   153.70   154.22  152.27    153.72    2909900       153.72
2016-10-14 2016-10-14   154.47   155.53  154.09    154.45    4358200       154.45
2016-10-17 2016-10-17   154.45   155.89  154.34    154.77    5890400       154.77
2016-10-18 2016-10-18   150.02   151.00  147.79    150.72   12705700       150.72
R> 

这篇关于将Zoo转换为数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆