Skip to content

Commit

Permalink
Add warning if .xts() index is datetime
Browse files Browse the repository at this point in the history
The documentation for .xts() says the 'index' argument should be a
numeric vector. Warn if it's a datetime because that has the potential
to create malformed xts objects (e.g. the numeric index is POSIXct but
its 'tzone' isn't UTC).
  • Loading branch information
joshuaulrich committed Apr 7, 2024
1 parent 5429845 commit 549a23a
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions R/xts.R
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,24 @@ function(x=NULL, index, tclass=c("POSIXct","POSIXt"),
if(check) {
if( !isOrdered(index, increasing=TRUE, strictly=unique) )
stop('index is not in ',ifelse(unique, 'strictly', ''),' increasing order')

if(timeBased(index)) {
msg <- paste0("'index' is not a plain numeric vector\n",
" this may create a malformed xts object and cause unexpected behaviors")
if(!inherits(index, tclass)) {
iclass <- class(index)
fmt <- "\n * index class (%s) does not match 'tclass' argument (%s)"
msg <- paste0(msg,
sprintf(fmt,
paste(iclass, collapse = ", "),
paste(tclass, collapse = ", ")))
}
if(isTRUE(tzone(index) != tzone)) {
fmt <- "\n * index timezone (%s) does not match 'tzone' argument (%s)"
msg <- paste0(msg, sprintf(fmt, dQuote(tzone(index)), dQuote(tzone)))
}
warning(msg)
}
}

index_out <- index
Expand Down

0 comments on commit 549a23a

Please sign in to comment.