Reputation: 403
Example Data:
structure(c(-0.0752423128397812, -0.00667756345500559, 0.127210629285125,
-0.139921096245914, 0.0652869973391721, -0.0426597532279215,
0.0900627738506856, 0.0181364458126518, 0.0655042896419282, 0.00433434751877004,
-0.0265985905707364, 0.0479551496911459), class = c("xts", "zoo"
), .indexCLASS = "Date", tclass = "Date", .indexTZ = "UTC", tzone = "UTC", index = structure(c(1451606400,
1454284800, 1456790400, 1459468800, 1462060800, 1464739200, 1467331200,
1470009600, 1472688000, 1475280000, 1477958400, 1480550400), tzone = "UTC", tclass = "Date"), .Dim = c(12L,
1L), .Dimnames = list(NULL, "AAPL.Returns"))
How do I convert the index of an object, in this case, the Date column, into a new column labelled Date?
Edit:
> head(Stock1_returns)
AAPL.Returns
2007-01-01 -0.006489744
2007-02-01 -0.013064271
2007-03-01 0.098097127
2007-04-01 0.074157809
2007-05-01 0.214328635
2007-06-01 0.007013805
Upvotes: 3
Views: 1813
Reputation: 23598
For turning a xts object into a dataframe with the date column you can use the following code. You use index to get the date index of the xts object and coredata for all the data contained in the xts object.
# my_xts is based on data from OP
df1 <- data.frame(Date = index(my_xts), coredata(my_xts) )
# show resulting structure
str(df1)
'data.frame': 12 obs. of 2 variables:
$ Date : Date, format: "2016-01-01" "2016-02-01" "2016-03-01" "2016-04-01" ...
$ AAPL.Returns: num -0.07524 -0.00668 0.12721 -0.13992 0.06529 ...
# outcome
df1
Date AAPL.Returns
1 2016-01-01 -0.075242313
2 2016-02-01 -0.006677563
3 2016-03-01 0.127210629
4 2016-04-01 -0.139921096
5 2016-05-01 0.065286997
6 2016-06-01 -0.042659753
7 2016-07-01 0.090062774
8 2016-08-01 0.018136446
9 2016-09-01 0.065504290
10 2016-10-01 0.004334348
11 2016-11-01 -0.026598591
12 2016-12-01 0.047955150
Upvotes: 7