Saturday, 3 February 2018

r - Converting a numeric matrix into a data.table (or data.frame)



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.



Answer



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
...

No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...