Search code examples
rdata-conversion

Convert xts/zoo object to data.frame in R


I have a data object called NKLA that looks like this:

> 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

But when I try to convert it to data.frame like

  • this as suggested here: data.frame(date=index(NKLA), coredata(NKLA))
  • or this, suggested here: as.data.table(NKLA)
  • or this, suggested here: as.data.frame.matrix(NKLA)
  • but I also found this: as.data.frame.table(NKLA)
  • and this: as.data.table(NKLA)
  • and this too: as.data.frame(NKLA)

I each time get an [1] "xts" "zoo" to the query class(NKLA).

My question:

  • How do I convert an xts/zoo object into a data.frame object?

Any help appreciated.


System used:

  • R version: 4.1.1 (2021-08-10)
  • RStudio version: 1.4.1717
  • OS: macOS Catalina version 10.15.7

Solution

  • We could use fortify.zoo

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

    -output

    > 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
    

    data

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