Skip to content

Commit

Permalink
Make as.matrix on zero-width xts similar to zoo
Browse files Browse the repository at this point in the history
Calling as.matrix() on a zero-width xts object results in an error
because dimnames cannot be set on a non-array (i.e. an object without
dims).  as.matrix.zoo() has special cases for zoo objects that are
missing one or more dims.

Refactor as.matrix.xts() to follow the pattern in as.matrix.zoo(), so
the two functions behave similarly.

Fixes #130.
  • Loading branch information
joshuaulrich committed Jul 30, 2017
1 parent c87c703 commit 32d74e6
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
30 changes: 27 additions & 3 deletions R/matrix.R
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,34 @@
# functions for matrix <--> xts conversions
`as.matrix.xts` <-
function(x, ...) {
# This function follows the pattern of as.matrix.zoo()
cd <- coredata(x)
dimnames(cd) <- list( as.character(index(x)), colnames(x) )
cd
# structure(coredata(x), dimnames=list(as.character(index(x)), colnames(x)))
y <- as.matrix(cd, ...)

if (length(cd) == 0) {
dim(y) <- c(0, 0)
}
# colnames
if (length(y) > 0) {
cnx <- colnames(x)
if (length(cnx) > 0) {
colnames(y) <- cnx
} else {
cn <- deparse(substitute(x), width.cutoff = 100, nlines = 1)
if (ncol(x) == 1) {
colnames(y) <- cn
} else {
colnames(y) <- paste(cn, 1:ncol(x), sep = ".")
}
}
} else if (nrow(y) != length(.index(x))) {
dim(y) <- c(length(.index(x)), 0)
}
# rownames
if (!is.null(y) && nrow(y) > 0 && is.null(rownames(y))) {
rownames(y) <- as.character(index(x))
}
y
}

`re.matrix` <-
Expand Down
8 changes: 8 additions & 0 deletions inst/unitTests/runit.matrix.R
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,11 @@ test.matrix_reclass_subset_as.xts_j1 <- function() {
test.matrix_reclass_subset_matrix_j1 <- function() {
checkIdentical(sample.matrix[,1,drop=FALSE],reclass(try.xts(sample.matrix[,1,drop=FALSE])))
}

# zero-width to matrix
test.zero_width_xts_to_matrix <- function() {
x <- .xts(,1)
xm <- as.matrix(x)
zm <- as.matrix(as.zoo(x))
checkIdentical(xm, zm)
}

0 comments on commit 32d74e6

Please sign in to comment.