Skip to content

Commit

Permalink
Add tclass and class if index has no attr
Browse files Browse the repository at this point in the history
Some users may set the index using attr<- instead of using the API, as
they should. This may result in a malformed index (e.g. a numeric
vector with no tclass or tzone attributes).

This can cause errors in other xts code. This commit fixes the case
where a call to index() on a malformed xts object throws an error at
the switch() statement, because value[[1]] is "". This case breaks
existing code in the twsInstrument package.

Throw a warning to let users know they're being naughty, and set the
tclass and class to POSIXct to avoid breaking things downstream.

Fixes #297.
  • Loading branch information
joshuaulrich committed Aug 4, 2019
1 parent 566ac0d commit a79391a
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
9 changes: 7 additions & 2 deletions R/index.R
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,13 @@
index.xts <- time.xts <-
function(x, ...) {
value <- tclass(x)
if(is.null(value))
return(.index(x))
if(is.null(value) || !nzchar(value)) {
warning("index does not have a ", sQuote("tclass"), " attribute\n",
" returning c(\"POSIXct\", \"POSIXt\")")
ix <- .index(x)
attr(ix, "tclass") <- attr(ix, "class") <- c("POSIXct", "POSIXt")
return(ix)
}
# if tclass is Date, POSIXct time is set to 00:00:00 GMT. Convert here
# to avoid ugly and hard to debug TZ conversion. What will this break?
if(value[[1]] == "Date")
Expand Down
9 changes: 9 additions & 0 deletions inst/unitTests/runit.index.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
test.get_index_does_not_error_if_index_has_no_attributes <- function() {
x <- .xts(1:3, 1:3, tzone = "UTC")

ix <- index(x)
ix <- ix + 3

attr(x, "index") <- 4:6
checkEquals(index(x), ix)
}

0 comments on commit a79391a

Please sign in to comment.