user2543622
user2543622

Reputation: 6756

R matrix getting row and column number and actual value

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

Answers (2)

ivan866
ivan866

Reputation: 582

data.frame(which(B==B, arr.ind=TRUE), value=as.vector(B))

Upvotes: 0

akrun
akrun

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

Related Questions