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

as.matrix.xts fails when zero columns #130

Closed
DarrenCook opened this issue Jan 8, 2016 · 1 comment
Closed

as.matrix.xts fails when zero columns #130

DarrenCook opened this issue Jan 8, 2016 · 1 comment
Assignees
Labels

Comments

@DarrenCook
Copy link

The xts:::as.matrix.xts function (

xts/R/matrix.R

Line 23 in 016b7cd

`as.matrix.xts` <-
) goes wrong when the xts object has zero-columns:

> xts:::as.matrix.xts(xts(c(),as.Date("2015-01-01")))
Error in dimnames(cd) <- list(as.character(index(x)), colnames(x)) : 
  'dimnames' applied to non-array

A first try at a patch looks like:

as.matrix.xts = function (x, ...) 
{
    if(length(x) == 0)cd <- matrix(,nrow=1,ncol=0)
    else cd <- coredata(x)
    dimnames(cd) <- list(as.character(index(x)), colnames(x))
    cd
}

I think it needs to be a bit more generic? But this was enough for me, and fixes a unit test that was complaining:

Error in dimnames(cd) <- list(as.character(index(x)), colnames(x)) : 
  'dimnames' applied to non-array
12: as.matrix.xts(x)
11: as.matrix(x)
10: as.vector(as.matrix(x), mode = mode)
9: as.vector.zoo(x, mode)
8: as.vector(x, mode)
7: as.vector(target)
6: all.equal.numeric(target, current, ...)
5: all.equal.default(target[[i]], current[[i]], check.attributes = check.attributes, 
       use.names = use.names, ...)
4: all.equal(target[[i]], current[[i]], check.attributes = check.attributes, 
       use.names = use.names, ...)
3: all.equal.list(target, current, tolerance = tolerance, ...)
2: all.equal(target, current, tolerance = tolerance, ...)
1: checkEquals(result, expected)
@joshuaulrich joshuaulrich self-assigned this Jan 27, 2016
@joshuaulrich
Copy link
Owner

Thanks for the report. Here's a simplified example:

R> as.matrix(xts::.xts(,1))
Error in dimnames(cd) <- list(as.character(index(x)), colnames(x)) : 
  'dimnames' applied to non-array

Versus what you get with zoo:::as.matrix.zoo:

R> as.matrix(zoo::zoo(,1))

1
R> str(as.matrix(zoo::zoo(,1)))
 num[1, 0 ] 
 - attr(*, "dimnames")=List of 2
  ..$ : chr "1"
  ..$ : NULL

I think your proposed function provides similar results, but I'll likely follow the pattern in zoo:::as.matrix.zoo in case there's some edge case differences I'm not spotting.

@joshuaulrich joshuaulrich added this to the Release 0.10-1 milestone Jul 8, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants