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

Inconsistent behaviour zero length index #363

Closed JasperSch closed 2 years ago

JasperSch commented 2 years ago

Description

xts:::index.xts() returns integer(0) instead of .POSIXct(character(0)) for a zero length xts object ordered by POSIXct values. Searched for similar issues before opening this one, but didn't find this exact problem. Noticed this inconsistency was intentionally introduced ( eac6e7b73ac4e38cb394ece1473bc7b6c008a8dd) for compatibility reasons with zoo, but as far as I can tell, zoo must in the meantime has changed its behaviour.

Minimal, reproducible example

Example shows inconsistent behaviour for POSIXct and consistent behaviour for Date. The behaviour for zoo objects is also shown.

library(xts)
timeXts <- xts(1, as.POSIXct("2000-01-01"))
dateXts <- xts(1, as.Date("2000-01-01"))
xts:::index.xts(timeXts)
# [1] "2000-01-01 CET"
xts:::index.xts(timeXts[0,])
# integer(0)
xts:::index.xts(dateXts)
# [1] "2000-01-01"
xts:::index.xts(dateXts[0,])
# Date of length 0

library(zoo)
timeZoo <- zoo(1, as.POSIXct("2000-01-01"))
dateZoo <- zoo(1, as.Date("2000-01-01"))
zoo::index(timeZoo)
# [1] "2000-01-01 CET"
zoo::index(timeZoo[0,])
# POSIXct of length 0
zoo::index(dateZoo)
# [1] "2000-01-01"
zoo::index(dateZoo[0,])
# Date of length 0

Session Info

> sessionInfo()
R version 3.6.3 (2020-02-29)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 20.04.3 LTS

Matrix products: default
BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0

locale:
 [1] LC_CTYPE=en_GB.UTF-8          LC_NUMERIC=C                 
 [3] LC_TIME=en_GB.UTF-8           LC_COLLATE=en_GB.UTF-8       
 [5] LC_MONETARY=en_GB.UTF-8       LC_MESSAGES=en_GB.UTF-8      
 [7] LC_PAPER=en_GB.UTF-8          LC_NAME=en_GB.UTF-8          
 [9] LC_ADDRESS=en_GB.UTF-8        LC_TELEPHONE=en_GB.UTF-8     
[11] LC_MEASUREMENT=en_GB.UTF-8    LC_IDENTIFICATION=en_GB.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] xts_0.12.1.2 zoo_1.8-9    rj_4.0.4-2  

loaded via a namespace (and not attached):
[1] compiler_3.6.3  tools_3.6.3     rj.gd_4.0.4-2   grid_3.6.3     
[5] lattice_0.20-41

Proposed solution:

Drop line 41-42 in index.R:

  if(length(x.index) == 0)
    return(integer())

EDIT: opened up a PR.