1
votes

I have a data frame data that looks like this:

dim(data)
# [1] 66955      2
library(chron)
data <- structure(list(`Date-Time` = structure(c(11320.6592476852,
  11320.6661921296, 11324.3958564815, 11324.4022569444),
  format = structure(c("y/m/d", "h:m:s"), .Names = c("dates", "times")),
  origin = structure(c(1, 1, 1970), .Names = c("month", "day", "year")),
  class = c("chron", "dates", "times")), Price = c(14.8125, 14.875,
  14.9375, 14.9375)), .Names = c("Date-Time", "Price"),
  row.names = 18620:18623, class = "data.frame")

The first column of data is of class "chron" "dates" "times". The date-time format is (yy/mm/dd h:m:s). I'm attempting to convert data[,2] to a xts object in order to use then the function makeReturns.

I tried:

library(xts)
as.xts(data[,2] , order.by=data[,1], format=c(dates="y/m/d", times="h:m:s"))

But this gives me the following (for the rows above):

                       [,1]
(NA NA)             14.8125
(NA NA)             14.8750
(01/01/02 09:30:02) 14.9375
(01/01/02 09:39:15) 14.9375

That is, it doesn't recognize the first two rows (with date-time format (00/12/29 15:49:19) and (00/12/29 15:59:19)) as yy/mm/dd (and h:m:s). In fact in the first two rows, the year is "00" (2000), and is not converted, while in the 3rd and 4th row, the years is "01" (2001), which he converts, but as a day or month.

How can I make sure that everything is converted to its such that the original format doesn't change? I've tried several variations in format=" " but nothing worked.

1

1 Answers

2
votes

chron doesn't seem to have a as.POSIXct method, and the default as.POSIXct method probably doesn't handle timezones the way you'd want it to, so you need to convert the first column of data to character and then coerce to POSIXct.

> xts(data[,2], as.POSIXct(as.character(data[,1]), format="(%y/%m/%d %H:%M:%S)"))
                       [,1]
2000-12-29 15:49:19 14.8125
2000-12-29 15:59:19 14.8750
2001-01-02 09:30:02 14.9375
2001-01-02 09:39:15 14.9375