将数字矩阵转换为data.table(或data.frame) [英] Converting a numeric matrix into a data.table (or data.frame)

查看:809
本文介绍了将数字矩阵转换为data.table(或data.frame)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个带有标记的行和列的数字矩阵:

  1 2 3 4 
a 6 7 8 9
b 8 7 5 7
c 8 5 4 1
d 1 6 3 2



我想要一个data.table(或data.frame然后我可以转换)的形式:

  col行值
1 a 6
1 b 8
1 c 8
1 d 1
2 a 7
2 b 7
2 c 5
2 d 6
...



任何提示赞赏。

解决方案

使用来自reshape2的融化

  b $ b #Fake data 
x< - matrix(1:12,ncol = 3)
colnames(x)< - letters [1:3]
rownames(x) - 1:4
xm< - melt(x)
xm

Var1 Var2值
1 1 a 1
2 2 a 2
3 3 a 3
4 4 a 4
...


Hoping there's a simple answer here but I can't find it anywhere.

I have a numeric matrix with labelled rows and columns:

     1    2    3    4
a    6    7    8    9
b    8    7    5    7
c    8    5    4    1
d    1    6    3    2

I would like a data.table (or a data.frame I can then convert) of the form:

    col     row    value
    1       a      6
    1       b      8
    1       c      8
    1       d      1
    2       a      7
    2       b      7
    2       c      5
    2       d      6
    ...

Any tips appreciated.

解决方案

Use melt from reshape2:

library(reshape2)
#Fake data
x <- matrix(1:12, ncol = 3)
colnames(x) <- letters[1:3]
rownames(x) <- 1:4
x.m <- melt(x)
x.m

   Var1 Var2 value
1     1    a     1
2     2    a     2
3     3    a     3
4     4    a     4
...

这篇关于将数字矩阵转换为data.table(或data.frame)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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