R - 从矩阵创建有序列表 [英] R - Create a ordered list from a matrix

查看:25
本文介绍了R - 从矩阵创建有序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好!

我有这个 24x24 矩阵,其中包含 1-24 的大量数字.我想将每个具有 X 值(例如 3)的单元格转换为第 X 行的 row.name(例如 name3)

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)

我有什么

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

我现在想要做的是将所有这些数字转换成一个字符串,相当于第 i 行名称,因此 1 应该转换为 name1 等等.

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.

我需要什么

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.

谢谢!//香港

推荐答案

使用基本的 [ 将值与行名匹配.

Use basic [ to match the values to the rownames.

这是一个例子.

假设我们从这个开始:

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

这里是 rownames(m)[m] 的样子:

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"

这篇关于R - 从矩阵创建有序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆