4

This is an extension of this question R xts and data.table.

I see as.xts.data.table is a new addition to the data.table package.

When I set dates with IDate (integer dates), I then get errors when looking at the table after an xts conversion with this error message:

Error in index.xts(x[1, ]) : unsupported ‘indexClass’ indexing type: IDate

CODE SNIPPET

library(data.table)
library(xts)

# I am setting dates as IDate here in example, but in my code 
#   I get a subset from elsewhere
dt <- data.table(date = c(as.IDate("2014-12-31"),
                          as.IDate("2015-12-31"),
                          as.IDate("2016-12-31")), 
                 nav = c(100,101,99),
                 key = "date")

str(dt)
# Classes ‘data.table’ and 'data.frame':    3 obs. of  2 variables:
#   $ date: IDate, format: "2014-12-31" "2015-12-31" ...
# $ nav : num  100 101 99
# - attr(*, "sorted")= chr "date"
# - attr(*, ".internal.selfref")=<externalptr> 


#convert to xts for PerformanceAnalytics (IDate not supported)
dt.xts <- as.xts.data.table(dt) # seems to work okay but...

str(dt.xts) # gives indexing type error above

I understand IDate is still developing out - "Still experimental!". What is the best way to get rid of the IDate type to use xts in the interim? [I tried forcing the type to no avail - as.xts(as.Date(dt$date)) ]

Can a future as.xts.data.table fix the IDates?

R3.2.2. versions: xts: 0.9-7 zoo: 1/7-12 data.table: 1.9.6

Community
  • 1
  • 1
micstr
  • 5,080
  • 8
  • 48
  • 76

1 Answers1

3

Update on 2016-04-13:
This has just been fixed in recent development version of data.table. You don't need to handle conversion of IDate any more. Code from the question will work just fine.
Below outdated answer, useful for those on data.table 1.9.6 or lower.


You need to change your IDate field to Date before converting to xts. IDate and ITime types were not considered when as.xts method was developed.
Patch to support that can be made, there is already one bugfix related to xts waiting to be merged.
Solution to your problem:

library(data.table)
library(xts)
dt <- data.table(date = c(as.IDate("2014-12-31"),
                          as.IDate("2015-12-31"),
                          as.IDate("2016-12-31")), 
                 nav = c(100,101,99),
                 key = "date")
dt[, date := as.Date(as.integer(date))]
dt.xts <- as.xts.data.table(dt)
jangorecki
  • 16,384
  • 4
  • 79
  • 160
  • Thanks @jangorecki. I did a workaropund like this. The one problem with dt[, date := as.Date(as.integer(date))] - it strips out the key as "date" is seen to have changed. (Others be aware of this and then rekey your table with `setkey()`) – micstr Jan 21 '16 at 08:50