将日期列添加到XTS对象

时间:2018-11-04 18:16:12

标签: r indexing xts

示例数据:

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"))

如何将对象的索引(在这种情况下为Date列)转换为标记为Date的新列?

编辑:

> 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

1 个答案:

答案 0 :(得分:3)

要使用日期列将xts对象转换为数据框,可以使用以下代码。您可以使用index获取xts对象的日期索引和xts对象中包含的所有数据的coredata。

# 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
相关问题