Search code examples
rxtstibble

What is the best way to transform an xts into a tibble


As of tibble package version 2.0.1 what is the best way to convert an xts object into a tibble? Consider the following example:

library(tibble)
library(xts)

myxts <- xts(matrix(1:4, 2, 2), 
  order.by = seq.Date(from = as.Date("2019-02-26"), 
  length.out = 2, 
  by = "d"))

as_tibble(myxts)

This gives a warning:

Warning message: Calling as_tibble() on a vector is discouraged, because the behavior is likely to change in the future. Use enframe(name = NULL) instead.

However using enframe results in an error:

enframe(myxts, name = NULL)

Error: x must not have more than one dimension. length(dim(x)) must be zero or one, not 2.

I am aware of the timetk package which has a function to convert xts objects into tibbles. However, this package is orphaned so I would rather avoid it.

Thank you for you feedback.

EDIT: I would be interested in a tidyverse solution to this problem: of course it is possible to first transform the xts object into an arbitrary object (e.g. a dataframe) and then into a tibble. But shouldn't there be a direct way as well?

EDIT2: As of tibble package version 3.0.3 the warning does not appear anymore. In particular one can use the line in Yakov-vc's answer to do a 'tidy' transformation.


Solution

  • How about as_tibble(xts) %>% add_column(day = index(xts), .before = 1)