0
votes

I have the following matrix:

mymatrix <- matrix(1:16, nrow = 4, ncol = 4, dimnames = list(letters[1:4], 1:4))

I would like to reverse the order of row names (without changing matrix cell values) for some specific rows, for instance row b and row c. How could I manage it? In fact is similar to just rename these rows, but I have to do that for many rows grouped in different places across the matrix and I would like to do it in a single step.

Thank you very much in advance!

1

1 Answers

0
votes

Put the rows you want to reverse in a list, then do it in a loop:

mymatrix <- matrix(1:12, nrow = 4, ncol = 4, dimnames  =list(letters[1:4], 1:4))

to_reverse = list(c("b", "c"), c("a", "d"))
for (i in seq_along(to_reverse)) {
  ind = row.names(mymatrix) %in% to_reverse[[i]]
  row.names(mymatrix)[ind] = rev(row.names(mymatrix)[ind])
}
mymatrix
#   1 2  3 4
# d 1 5  9 1
# c 2 6 10 2
# b 3 7 11 3
# a 4 8 12 4