As maintainer of the Matrix
package: Using dimnames for sparseMatrix objects is allowed in construction,
and for column names even of importance, notably e.g. for sparse model matrices (in glmnet
etc).
but for efficiency reasons (and partly lack of use cases and hence "not yet
implemented") they are not always propagated, e.g., IIRC, in matrix multiplications.
The main reasons for this "semi discouraged" support is the fact that sparse Matrices are particularly important when very large in the sense of nrow(.) * ncol(.)
being large.
In such cases, carrying (and copying !!) hundreds of thousands of row (and column) names is costly.
After all this caveat, of course I acknowledge you've asked a well valid question, and you may not have a choice for now and indeed need to work with row and column names instead of integer indices.
Yes, you are (almost) right: Using
M <- Matrix(0, n,m, dimnames=....)
for(i in ...)
for(j in ...)
M[i,j] <- ...
is never a good idea for sparseMatrix
objects (i.e. all Matrix objects inheriting from sparseMatrix
).
Rather, using sparseMatrix(...., dimnames = ..)
.. by the way noting that using the dimnames
argument is more efficient than setting colnames
and rownames
separately afterwards.