R - Create a ordered list from a matrix

2019-08-16 07:44发布

问题:

Hi there!

I have this 24x24 matrix with a lot of numbers from 1-24. Where I want to turn every cell with the value of X (eg. 3) into the row.name of the X'th row (eg. name3)

What I have

row.names         V1    V2   V3
name1              1     3   10
name2              3    20    1
name3              5    13    2
...               ..    ..   ..
name24            19     3    4

What I want to do now, is turn all these numbers into a character string equvivalent to the i'th row name so a 1 should be converted to name1 and so forth.

What I need

row.names             V1        V2       V3
name1              name1     name3   name10
name2              name3    name20    name1
name3              name5    name13    name2
...                   ..        ..       ..
name24             name19    name3    name4

I figured it may be nessesary to convert the matrix into a dataframe, but I don't know exacly how to get there from what I have.

Thanks! //HK

回答1:

Use basic [ to match the values to the rownames.

Here's an example.

Assume we're starting with this:

set.seed(1)
m <- matrix(sample(1:3, 12, TRUE), 
            ncol = 4, 
            dimnames = list(letters[1:3], LETTERS[1:4]))
m
#   A B C D
# a 1 3 3 1
# b 2 1 2 1
# c 2 3 2 1

Here's what rownames(m)[m] looks like:

rownames(m)[m]
# [1] "a" "b" "b" "c" "a" "c" "c" "b" "b" "a" "a" "a"

Use [] to preserve the dims of the original matrix while replacing the values:

m[] <- rownames(m)[m]
m
#   A   B   C   D  
# a "a" "c" "c" "a"
# b "b" "a" "b" "a"
# c "b" "c" "b" "a"