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

后端 未结 3 1357
一个人的身影
一个人的身影 2021-02-04 11:02

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          


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-02-04 11:52

    Assuming 'm' is your matrix...

    data.frame(col = rep(colnames(m), each = nrow(m)), 
               row = rep(rownames(m), ncol(m)), 
               value = as.vector(m))
    

    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.

提交回复
热议问题