Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inconsistent conversions to/from zoo with zero-length coredata #228

Closed
joshuaulrich opened this issue Mar 14, 2018 · 3 comments
Closed

Inconsistent conversions to/from zoo with zero-length coredata #228

joshuaulrich opened this issue Mar 14, 2018 · 3 comments
Assignees

Comments

@joshuaulrich
Copy link
Owner

Converting a zero-length object to zoo and back to xts loses the dim and dimname attributes.

# zero-length zoo
z <- zoo(matrix(numeric(0), 3, 3)[0,], numeric(0))

# can't convert to xts
as.xts(z)
### Error in xts(coredata(x), order.by = order.by, frequency = frequency,  :
###   order.by requires an appropriate time-based object

# zero-length xts
x <- .xts(matrix(numeric(0), 3, 3)[0,], numeric(0))

# can convert to zoo...
zx <- as.zoo(x)

# ...but can't convert back to xts
xzx <- as.xts(zx)
### Error in xts(coredata(x), order.by = order.by, frequency = frequency,  :
###   order.by requires an appropriate time-based object

This is partially caused by as.zoo.xts() setting coredata to NULL. It might also be related to the fix for #223.

@joshuaulrich
Copy link
Owner Author

It's not an issue that as.xts(z) doesn't work because z doesn't have a time-based index. It works if the index is time-based.

z <- zoo(matrix(numeric(0), 3, 3)[0,], .POSIXct(numeric(0)))
xz <- as.xts(z)

We have to change zoo:::as.zoo.xts() in order for all.equal(x, xzx) to be TRUE. It needs to only set y <- NULL if it's zero-length and has no dims.

The patch is:

diff --git a/pkg/zoo/R/as.zoo.R b/pkg/zoo/R/as.zoo.R
index d1a8c99..0f5dc42 100644
--- a/pkg/zoo/R/as.zoo.R
+++ b/pkg/zoo/R/as.zoo.R
@@ -52,7 +52,7 @@ as.zoo.timeSeries <- function(x, ...) {
 
 as.zoo.xts <- function(x, ...) {
   y <- coredata(x)
-  if (length(y) == 0) {
+  if (length(y) == 0 && is.null(dim(y))) {
     y <- NULL
   }
   zoo(y, order.by = index(x), ...)

@joshuaulrich joshuaulrich self-assigned this Mar 5, 2023
@joshuaulrich
Copy link
Owner Author

This is fixed in zoo >= 1.8-12.

@zeileis
Copy link
Collaborator

zeileis commented Mar 5, 2023

Thanks, much appreciated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants