Reputation: 6756
I have a matrix as below
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
I would like to create a data.frame with 3 columns: row number, column number and actual value from above matrix. I am thinking of writing 2 for loops. Is there a more efficient way to do this?
The output that i want (i am showing only first 2 rows below)
rownum columnnum value
1 1 2
1 2 1
Upvotes: 2
Views: 1831
Reputation: 886938
Try
cbind(c(row(B)), c(col(B)), c(B))
Or
library(reshape2)
melt(B)
As per @nicola's comments, the output needed may be in the row-major order. In that case, take the transpose of the matrix and do the same
TB <- t(B)
cbind(rownum = c(col(TB)), colnum = c(row(TB)), value = c(TB))
Upvotes: 5