SCM

[#6751] as(<ddiMatrix>, "matrix") loses dimnames

Date:
2021-12-07 19:18
Priority:
3
State:
Closed
Submitted by:
Mikael Jagan (jaganmn)
Assigned to:
Nobody (None)
Hardware:
All
Product:
None
Operating System:
All
Component:
None
Version:
None
Severity:
None
Resolution:
Fixed
URL:
Summary:
as(<ddiMatrix>, "matrix") loses dimnames

Detailed description
`Matrix/R/diagMatrix.R` contains:

```
.ddi2mat <- function(from)
base::diag(if(from@diag == "U") as1(from@x) else from@x, nrow = from@Dim[1])
setAs("ddiMatrix", "matrix", .ddi2mat)
```

`.ddi2mat(from)` does not use `from@Dimnames`, so `as(<ddiMatrix>, "matrix")` loses `[dD]imnames`.

```
> library("Matrix")
> x <- Diagonal(n = 5, x = 1:5)
> dimnames(x)[] <- list(letters[1:5])
> x
5 x 5 diagonal matrix of class "ddiMatrix"
a b c d e
a 1 . . . .
b . 2 . . .
c . . 3 . .
d . . . 4 .
e . . . . 5
> as(x, "matrix")
[,1] [,2] [,3] [,4] [,5]
[1,] 1 0 0 0 0
[2,] 0 2 0 0 0
[3,] 0 0 3 0 0
[4,] 0 0 0 4 0
[5,] 0 0 0 0 5
```

A patch:

```
.ddi2mat <- function(from) {
res <- base::diag(if(from@diag == "U") as1(from@x) else from@x, nrow = from@Dim[1])
dimnames(res) <- from@Dimnames
res
}
```

Comments:

Message  ↓
Date: 2021-12-08 16:57
Sender: Martin Maechler

Thank you,
yes it's .ddi2mat() that needs to be fixed.
Back then I think I had thought nobody would use dimnames on a diagonal matrix ... and indeed that *is* pretty rare.
But still for compatibility reasons, I've fixed this in r3418:
https://r-forge.r-project.org/scm/viewvc.php/pkg/Matrix/R/diagMatrix.R?r1=3417&r2=3418&pathrev=3418&root=matrix&view=diff&diff_format=h

Date: 2021-12-07 19:30
Sender: Mikael Jagan

Related thread on Stack Overflow: https://stackoverflow.com/questions/68077229/convert-from-sparse-matrix-to-dense-matrix-without-losing-dimnames/70256476

Attached Files:

Changes

Field Old Value Date By
status_idOpen2021-12-08 16:57mmaechler
close_dateNone2021-12-08 16:57mmaechler
ResolutionNone2021-12-08 16:57mmaechler
Thanks to:
Vienna University of Economics and Business Powered By FusionForge