【问题标题】:Convert xts/zoo object to data.frame in R将 xts/zoo 对象转换为 R 中的 data.frame
【发布时间】:2021-11-12 13:02:49
【问题描述】:

我有一个名为 NKLA 的数据对象,如下所示:

> class(NKLA)
[1] "xts" "zoo"

> head(NKLA)
           NKLA.Open NKLA.High NKLA.Low NKLA.Close NKLA.Volume NKLA.Adjusted
2018-06-11      9.57      9.58     9.57       9.58      402600          9.58
2018-06-12      9.56      9.56     9.56       9.56      300000          9.56
2018-06-13      9.57      9.58     9.56       9.57      179100          9.57
2018-06-14      9.57      9.57     9.57       9.57           0          9.57
2018-06-15      9.57      9.57     9.57       9.57           0          9.57
2018-06-18      9.54      9.58     9.54       9.58         300          9.58

但是当我尝试将其转换为 data.frame 时

  • 建议here:data.frame(date=index(NKLA), coredata(NKLA))
  • 或者这个,建议hereas.data.table(NKLA)
  • 或者这个,建议hereas.data.frame.matrix(NKLA)
  • 但我也发现了这个:as.data.frame.table(NKLA)
  • 还有这个:as.data.table(NKLA)
  • 还有这个:as.data.frame(NKLA)

我每次查询class(NKLA)时都会得到一个[1] "xts" "zoo"

我的问题:

  • 如何将xts/zoo 对象转换为data.frame 对象?

任何帮助表示赞赏。


使用的系统:

  • R 版本:4.1.1 (2021-08-10)
  • RStudio 版本:1.4.1717
  • 操作系统:macOS Catalina 版本 10.15.7

【问题讨论】:

    标签: r data-conversion


    【解决方案1】:

    我们可以使用fortify.zoo

    library(zoo)
    df1 <- fortify.zoo(NKLA)
    

    -输出

    > str(df1)
    'data.frame':   6 obs. of  7 variables:
     $ Index        : POSIXct, format: "2018-06-11" "2018-06-12" "2018-06-13" "2018-06-14" ...
     $ NKLA.Open    : num  9.57 9.56 9.57 9.57 9.57 9.54
     $ NKLA.High    : num  9.58 9.56 9.58 9.57 9.57 9.58
     $ NKLA.Low     : num  9.57 9.56 9.56 9.57 9.57 9.54
     $ NKLA.Close   : num  9.58 9.56 9.57 9.57 9.57 9.58
     $ NKLA.Volume  : num  402600 300000 179100 0 0 ...
     $ NKLA.Adjusted: num  9.58 9.56 9.57 9.57 9.57 9.58
    

    数据

    NKLA <- structure(c(9.57, 9.56, 9.57, 9.57, 9.57, 9.54, 9.58, 9.56, 9.58, 
    9.57, 9.57, 9.58, 9.57, 9.56, 9.56, 9.57, 9.57, 9.54, 9.58, 9.56, 
    9.57, 9.57, 9.57, 9.58, 402600, 3e+05, 179100, 0, 0, 300, 9.58, 
    9.56, 9.57, 9.57, 9.57, 9.58), .Dim = c(6L, 6L), .Dimnames = list(
        NULL, c("NKLA.Open", "NKLA.High", "NKLA.Low", "NKLA.Close", 
        "NKLA.Volume", "NKLA.Adjusted")), index = structure(c(1528689600, 
    1528776000, 1528862400, 1528948800, 1529035200, 1529294400), tzone = "", tclass = c("POSIXct", 
    "POSIXt")), class = c("xts", "zoo"))
    

    【讨论】:

    • 感谢您的回答。不幸的是,您的解决方案似乎不起作用。尝试fortify.zoo(NKLA) 后,class(NKLA) 仍然呈现[1] "xts" "zoo"str(NKLA) 呈现An ‘xts’ object on 2018-06-11/2021-09-16 containing:...
    • @pdeli 如果您看到我的解决方案。它正在分配给新对象df1,如果你想更新你需要的原始对象NKLA &lt;- fortify.zoo(NKLA),请检查str(df1)
    • 你完全正确! NKLA &lt;- fortify.zoo(NKLA) 绝对完美。非常感谢。
    • @pdeli 如果可行,请考虑接受解决方案
    猜你喜欢
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    • 2014-05-17
    • 2011-03-31
    • 1970-01-01
    • 2020-03-07
    • 2020-02-03
    • 2018-06-20
    相关资源
    最近更新 更多