Converting a sparse Matrix object (from the Matrix package) to a plain old base-R dense matrix object appears to lose the row/column names.
m <- matrix(0, 3,3, dimnames = list(LETTERS[1:3], LETTERS[1:3]))
dimnames(m)
## [[1]]
## [1] "A" "B" "C"
##
## [[2]]
## [1] "A" "B" "C"
Converting to a Matrix is fine:
dimnames(M <- Matrix::Matrix(m))
## [[1]]
## [1] "A" "B" "C"
## [[2]]
## [1] "A" "B" "C"
But converting back appears to lose the row/column names:
dimnames(as.matrix(M))
## NULL
dimnames(as(M, "matrix"))
## NULL
I know I can work around it by storing the dimnames and then attaching them to the new object (see below), but I don't feel like I should have to ... am I missing either a transparent/better way of making the conversion, or a logical reason why dimnames should not be preserved when making this conversion??
## workaround/hack
dn <- dimnames(m)
m2 <- as.matrix(M)
dimnames(m2) <- dn
To clarify, I want to handle the case where M already exists has been defined but m hasn't (i.e. the old m[] <- trick to replace the contents of m while leaving its attributes unchanged doesn't seem to work ...)