Home > Software design >  How to print out the row names instead of their indices?
How to print out the row names instead of their indices?

Time:07-08

I have a matrix m and made some calculation on it, as the result I obtained a matrix ind. In the code below ind is the constant matrix.

k=10; n = 8
m <- matrix(c(1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 1, 1, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 1, 1, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 1, 1, 0,
              0, 0, 0, 0, 0, 0, 1, 0, 0, 1,
              0, 0, 0, 0, 1, 0, 1, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 1, 1,
              0, 1, 1, 0, 0, 1, 0, 1, 0, 0), n, k, byrow = TRUE) 
colnames(m)<-1:k; rownames(m)<-LETTERS[1:n]
# some calculation
ind <-matrix(c(
    1,    1,
    2,    2,
    3,    6,
    4,    7,
    5,    8), 5, 2, byrow = TRUE)

I need to output the row names of m matrix instead of row indeces.

My attempt is:

 noquote(rownames(m)[ind])
 [1] A B C D E A B F G H

Expected result is:

     [,1] [,2]
[1,]    A    A
[2,]    B    B
[3,]    C    F
[4,]    D    G
[5,]    E    H

CodePudding user response:

You can use subsetting as follow:

rn = ind

rn[] <- rownames(m)[ind]

     [,1] [,2]
[1,] "A"  "A" 
[2,] "B"  "B" 
[3,] "C"  "F" 
[4,] "D"  "G" 
[5,] "E"  "H" 

CodePudding user response:

You can use apply

apply(ind, 2, function(x) rownames(m)[x])
#     [,1] [,2]
#[1,] "A"  "A" 
#[2,] "B"  "B" 
#[3,] "C"  "F" 
#[4,] "D"  "G" 
#[5,] "E"  "H" 

CodePudding user response:

Here is a solution as you expect it, with noquotes

noquote(matrix(rownames(m)[ind], nrow(ind)), right = T)

-output

     [,1] [,2]
[1,]    A    A
[2,]    B    B
[3,]    C    F
[4,]    D    G
[5,]    E    H
  • Related