gpt4 book ai didi

r - 将日期列添加到 XTS 对象

转载 作者:行者123 更新时间:2023-12-01 07:46:33 24 4
gpt4 key购买 nike

示例数据:

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

最佳答案

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

# 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

关于r - 将日期列添加到 XTS 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53143906/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com