joshuaulrich / xts

Extensible time series class that provides uniform handling of many R time series classes by extending zoo.
http://joshuaulrich.github.io/xts/
GNU General Public License v2.0
220 stars 71 forks source link

tzone warning on '[' subset #310

Closed harvey131 closed 4 years ago

harvey131 commented 4 years ago

Description

A warning is generated by the [ subset method if index(x) does not have the tzone attribute. The tzone attribute of the index can be dropped by performing +/- difftime operations on index(x). This way of changing the index(x) is typically much faster than shift.time().

Expected behavior

The 'index.xts<-' operator could use tzone = '' by default for classes that are not in .classesWithoutTZ and where the tzone attribute of x is missing. See line 88 of index.R

Minimal, reproducible example

library(xts)
options(warn=2) # warnings as errors
n <- 1e3L
x <- .xts(runif(n, 1, n), 1:n)
x["1969-12-31 19:00:02"]  
# tzone attribute exists
attributes(index(x))  
# add a second to the index
index(x) = index(x) + 1
# tzone attribute is now dropped
attributes(index(x)) 
# warning/error is produced
x["1969-12-31 19:00:02"] 

Session Info

R 3.6.1
joshuaulrich commented 4 years ago

Thanks for the report! This is one of a few ways that the tzone attribute can be dropped. The more common one is when .index<- is used to update an index value (because the value may be numeric).

Please add to this issue if you find more instances where index attributes are being dropped when they shouldn't be. Thanks!

harvey131 commented 4 years ago

unit test:

x <- .xts(runif(10, 1, 10), 1:10)
stopifnot( 'tzone' %in% names(attributes(index(x))))
# add a second to the index
index(x) = index(x) + 1
# tzone attribute is now dropped
stopifnot( 'tzone' %in% names(attributes(index(x))))
joshuaulrich commented 4 years ago

It looks like this only happens when tzone = "", and it is caused by Ops.POSIXt. For example:

x <- .xts(1:3, 1:3, tzone = "UTC")
index(x) <- index(x) + 1
attr(.index(x), "tzone")  # UTC
### but...
x <- .xts(1:3, 1:3, tzone = "")
attributes(index(x) + 1)  # no tzone attribute
index(x) <- index(x) + 1
attr(.index(x), "tzone")  # NULL