R矩阵获取行列号和实际值

use*_*622 2 for-loop r matrix

我有一个矩阵如下

 B = matrix( 
   c(2, 4, 3, 1, 5, 7), 
   nrow=3, 
   ncol=2)

 B             # B has 3 rows and 2 columns 
 #    [,1] [,2] 
 #[1,]    2    1 
 #[2,]    4    5 
 #[3,]    3    7
Run Code Online (Sandbox Code Playgroud)

我想创建一个包含 3 列的 data.frame:行号、列号和来自上述矩阵的实际值。我正在考虑编写 2 个 for 循环。有没有更有效的方法来做到这一点?

我想要的输出(我只显示下面的前 2 行)

rownum columnnum value
1 1 2
1 2 1
Run Code Online (Sandbox Code Playgroud)

akr*_*run 5

尝试

cbind(c(row(B)), c(col(B)), c(B))
Run Code Online (Sandbox Code Playgroud)

或者

library(reshape2)
melt(B)
Run Code Online (Sandbox Code Playgroud)

根据@nicola 的评论,所需的输出可能按行优先顺序排列。在这种情况下,取矩阵的转置并执行相同的操作

TB <- t(B)
cbind(rownum = c(col(TB)), colnum = c(row(TB)), value = c(TB))
Run Code Online (Sandbox Code Playgroud)