Skip to content

Commit

Permalink
Make zero-length subset return same storage type
Browse files Browse the repository at this point in the history
Subsetting a zero-length xts object always returned a "logical" xts
object, regardless of the input type.

Fixes #376.
  • Loading branch information
joshuaulrich committed Oct 10, 2022
1 parent 9438df4 commit 5fe2673
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
4 changes: 3 additions & 1 deletion R/xts.methods.R
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,9 @@ function(x, i, j, drop = FALSE, which.i=FALSE,...)
i <- seq_len(nr)

if(length(x)==0) {
x.tmp <- .xts(rep(NA, length(i)), .index(x)[i], tclass(x), tzone(x),
cdata <- rep(NA, length(i))
storage.mode(cdata) <- storage.mode(x)
x.tmp <- .xts(cdata, .index(x)[i], tclass(x), tzone(x),
dimnames = list(NULL, colnames(x)))
return(x.tmp)
} else {
Expand Down
24 changes: 24 additions & 0 deletions inst/unitTests/runit.subset.R
Original file line number Diff line number Diff line change
Expand Up @@ -325,3 +325,27 @@ test.zero_length_subset_xts_returns_same_tclass <- function() {
checkTrue(tclass(x[0,]) == "POSIXct")
checkTrue(tzone(x[0,]) == "America/Chicago")
}

test.zero_length_subset_returns_same_storage_mode <- function() {
# integer
x <- .xts(matrix(integer(0), 0), integer(0))
checkEquals(storage.mode(x), storage.mode(x[0, ]))
checkEquals(storage.mode(x), storage.mode(x[0, 0]))
checkEquals(storage.mode(x), storage.mode(x[0, FALSE]))

x <- .xts(matrix(integer(0), 0, 2), integer(0))
checkEquals(storage.mode(x), storage.mode(x[0,]))
checkEquals(storage.mode(x), storage.mode(x[0, 1]))
checkEquals(storage.mode(x), storage.mode(x[0, c(TRUE, FALSE)]))

# numeric
x <- .xts(matrix(numeric(0), 0), integer(0))
checkEquals(storage.mode(x), storage.mode(x[0, ]))
checkEquals(storage.mode(x), storage.mode(x[0, 0]))
checkEquals(storage.mode(x), storage.mode(x[0, FALSE]))

x <- .xts(matrix(numeric(0), 0, 2), integer(0))
checkEquals(storage.mode(x), storage.mode(x[0,]))
checkEquals(storage.mode(x), storage.mode(x[0, 1]))
checkEquals(storage.mode(x), storage.mode(x[0, c(TRUE, FALSE)]))
}

0 comments on commit 5fe2673

Please sign in to comment.