我在R
中将一个动物园时间序列
转换成了一个数据框,日期成为了数据框的索引。有没有办法让日期以普通列的形式表示在数据框中?
monthly_df <- data.frame(monthly_zoo)
head(monthly_zoo)
head(monthly_df)
fortify.zoo(z)
将zoo对象z
转换为一个数据框,第一列等于索引。
library(zoo)
z <- zoo(1:3, as.Date("2000-01-01") + 0:2) # test object
fortify.zoo(z)
提供:
Index z
1 2000-01-01 1
2 2000-01-02 2
3 2000-01-03 3
ggplot2
(因此存在fortify
通用函数),则可以使用以下方式进行替代:library(ggplot2)
fortify(z)
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>
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>
cbind( index(IBM), data.frame(IBM))
我已经学会不信任 as.data.frame
。 - IRTFM
monthly_df$month <- rownames(monthly_df)
or usetibble::rownames_to_column
- alistaire