0
votes

I have a sparse matrix whose rows and columns names are numbers. I need to sort rows and columns so that they are increasing. However, dimnames can only be stored as characters, not integers or numbers, so that sorting dimnames does not give increasing sorting but rather treats numbers as words and sorts them alphabetically (for example, 10000001 comes before 1001).

Every time I try to change the type of the dimnames I get this error:

Error in dimnamesGets(x, value) : 
  invalid dimnames given for “dgCMatrix” object

Is there a way around this? Are there different types of matrices that allow for numerical dimnames?

1

1 Answers

1
votes

You can do a numeric conversion outside of the matrix to get the right order, then use that ordering on the character-class dimnames to sort. For example:

my_colnames = c("1", "11",  "2", "10", "12")
my_col_order = order(as.numeric(my_colnames))
my_colnames[my_col_order]
[1] "1"  "2"  "10" "11" "12"
# sorted correctly even though still character class