How can I change XTS to data.frame and keep Index?
Solution 1:
That's because the dates are rownames in your data.frame. You need to make them a separate column.
Try this:
data.frame(date=index(master_1), coredata(master_1))
Solution 2:
This is a bit of a sidebar, but the fortify(...)
function in package ggplot2
will convert a variety of objects to data frames suitable for use in ggplot(...)
, including xts
objects.
library(xts)
set.seed(1) # for reproducible example
master_1 <- xts(rnorm(10,mean=2,sd=0.1),as.POSIXct("2010-03-03")+30*(0:9))
library(ggplot2)
df <- fortify(master_1)
head(df)
# Index master_1
# 1 2010-03-03 00:00:00 1.937355
# 2 2010-03-03 00:00:30 2.018364
# 3 2010-03-03 00:01:00 1.916437
# 4 2010-03-03 00:01:30 2.159528
# 5 2010-03-03 00:02:00 2.032951
# 6 2010-03-03 00:02:30 1.917953
So if you're already using gggplot
this is an easy way to do it. Note that the index goes into a column named Index
(capital "I").