Converting a data frame to xts
This is clearly documented --- xts and zoo objects are formed by supplying two arguments, a vector
or matrix
carrying data and Date
, POSIXct
, chron
, ... type supplying the time information (or in the case of zoo the ordering).
So do something like
qxts <- xts(q[,-1], order.by=q[,1])
and you should be set.
Well, as.xts assumes by default that the dates are stored in the rownames of the data.frame. Hence the error message. A quick and dirty fix is:
rownames(q) = q[1]
as.xts(q)
But you get an extra column with the dates string. Ideally you would construct the data.frame with the dates as rownames to start with.
Here's a solution using the tidyquant
package, which contains a function as_xts()
that coerces a data frame to an xts object. It also contains as_tibble()
to coerce xts objects to tibbles ("tidy" data frames).
Recreate the data frame (note that the date-time class is used in "tidy" data frames, but any unambiguous date or date time class can be used):
> q
# A tibble: 3 × 2
t x
<dttm> <dbl>
1 2006-01-01 00:00:00 1
2 2006-01-01 01:00:00 2
3 2006-01-01 02:00:00 3
Use as_xts()
to convert to "xts" class. Specify the argument, date_col = t
, to designate the "t" column as the dates to use as row names:
> library(tidyquant)
> as_xts(q, date_col = t)
x
2006-01-01 00:00:00 1
2006-01-01 01:00:00 2
2006-01-01 02:00:00 3
The return is an xts
object with the proper date or date-times as row names.
Here is a posible solution:
library(timetk)
q <- xts::xts(q[,-1], order.by = q$t)