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.
Assuming 'm' is your matrix...
This executes extremely fast on a large matrix and also shows you a bit about how a matrix is made, how to access things in it, and how to construct your own vectors.
Use
melt
from reshape2:The
as.table
andas.data.frame
functions together will do this:You can use the function
data.table()
with the parameterkeep.rownames
to convert the matrix to the data.table class: