Skip to content

Commit

Permalink
Fix xts() for zero-row data.frame
Browse files Browse the repository at this point in the history
The xts() constructor would create an object with a list for coredata
when 'x' is a data.frame with no rows. We need to convert 'x' to a
matrix. Also throw an error if 'x' is a list.

Fixes #394.
  • Loading branch information
joshuaulrich committed Mar 2, 2023
1 parent 61c2200 commit 7452beb
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
7 changes: 7 additions & 0 deletions R/xts.R
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,13 @@ function(x=NULL,

if(is.null(x)) {
x <- numeric(0)
} else if (is.list(x)) {
# list or data.frame
if (is.data.frame(x)) {
x <- as.matrix(x)
} else {
stop("cannot convert lists to xts objects")
}
} else if (NROW(x) > 0) {
x <- as.matrix(x)
}
Expand Down
19 changes: 19 additions & 0 deletions inst/tinytest/test-xts.R
Original file line number Diff line number Diff line change
Expand Up @@ -368,3 +368,22 @@ if(requireNamespace("chron", quietly = TRUE)) {
expect_identical(tzone(x), "UTC", info = ".xts() non-UTC tzone is set to UTC (chron)")
expect_identical(tzone(y), "UTC", info = ".xts() non-UTC tzone is set to UTC (dates)")
}

### lists and zero-row data.frames
msg <- "cannot convert lists to xts objects"
expect_error(xts(list(1, 2), .Date(1:2)), msg, info = msg)
#expect_error(.xts(list(1, 2), 1:2), msg, info = msg)

zero_row_df <- data.frame(date = .Date(numeric(0)), x = numeric(0), y = numeric(0))
zero_row_xts <- xts(zero_row_df[, -1], zero_row_df[, 1])

expect_identical(names(zero_row_xts), names(zero_row_df)[-1],
info = "xts() keeps names for zero-row data.frame")
expect_equal(.Date(numeric(0)), index(zero_row_xts),
info = "xts() has zero-length Date index for zero-row data.frame with Date column")

zero_row_xts. <- .xts(zero_row_df[, -1], zero_row_df[, 1])
expect_identical(names(zero_row_xts.), names(zero_row_df)[-1],
info = ".xts() keeps names for zero-row data.frame")
expect_equal(.Date(numeric(0)), index(zero_row_xts.),
info = ".xts() has zero-length Date index for zero-row data.frame with Date column")

0 comments on commit 7452beb

Please sign in to comment.