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

Ops.xts on dim-less xts and matrix creates malformed xts objects #295

Closed joshuaulrich closed 5 years ago

joshuaulrich commented 5 years ago

Several permutations of calling binary operators on xts and matrix arguments results in a malformed xts object. If the xts object does not have a dim attribute, the result has a c("xts", "zoo") class, but no index attribute. The xts result will also have rownames if the matrix does.

data(sample_matrix)
x <- as.xts(sample_matrix[1:5, c(1,4)])
d <- coredata(x)
m <- as.matrix(x)
xv <- drop(x[,1])

# all these are okay: index, class, dim, dimnames (no rownames)
attributes(x-d)
attributes(x-m)
attributes(x-d[,1])
attributes(x-m[,1])

# these are various degrees of wrong
attributes(xv-d)      # no index
attributes(xv-m)      # no index, has rownames
attributes(xv-d[,1])  # okay
attributes(xv-m[,1])  # has names

# not clear what is the correct behavior here
# these pick up the dim attribute from the 1-column matrix
attributes(xv-d[, 1, drop = FALSE])
attributes(xv-m[, 1, drop = FALSE])  # has rownames

Session Info

These were found as part of testing #245.

For reference, the behavior of the last 2 results is consistent with the current version (0.11-2):

data(sample_matrix)
x <- as.xts(sample_matrix[1:5, c(1,4)])
d <- coredata(x)
m <- as.matrix(x)
xv <- drop(x[,1])

attributes(xv-d[, 1, drop = FALSE])
# $index
# [1] 1167717600 1167804000 1167890400 1167976800 1168063200
# attr(,"tzone")
# [1] ""
# attr(,"tclass")
# [1] "POSIXct" "POSIXt" 
# 
# $class
# [1] "xts" "zoo"
# 
# $.indexCLASS
# [1] "POSIXct" "POSIXt" 
# 
# $tclass
# [1] "POSIXct" "POSIXt" 
# 
# $.indexTZ
# [1] ""
# 
# $tzone
# [1] ""
# 
# $dim
# [1] 5 1
# 
# $dimnames
# $dimnames[[1]]
# NULL
# 
# $dimnames[[2]]
# [1] "Open"

attributes(xv-m[, 1, drop = FALSE])  # has rownames
# $index
# [1] 1167717600 1167804000 1167890400 1167976800 1168063200
# attr(,"tzone")
# [1] ""
# attr(,"tclass")
# [1] "POSIXct" "POSIXt" 
# 
# $class
# [1] "xts" "zoo"
# 
# $.indexCLASS
# [1] "POSIXct" "POSIXt" 
# 
# $tclass
# [1] "POSIXct" "POSIXt" 
# 
# $.indexTZ
# [1] ""
# 
# $tzone
# [1] ""
# 
# $dim
# [1] 5 1
# 
# $dimnames
# $dimnames[[1]]
# [1] "2007-01-02" "2007-01-03" "2007-01-04" "2007-01-05" "2007-01-06"
# 
# $dimnames[[2]]
# [1] "Open"