for loop - R matrix getting row and column number and actual value -


i have matrix below

 b = matrix(     c(2, 4, 3, 1, 5, 7),     nrow=3,     ncol=2)   b             # b has 3 rows , 2 columns   #    [,1] [,2]   #[1,]    2    1   #[2,]    4    5   #[3,]    3    7 

i create data.frame 3 columns: row number, column number , actual value above matrix. thinking of writing 2 loops. there more efficient way this?

the output want (i showing first 2 rows below)

rownum columnnum value 1 1 2 1 2 1 

try

cbind(c(row(b)), c(col(b)), c(b)) 

or

library(reshape2) melt(b) 

as per @nicola's comments, output needed may in row-major order. in case, take transpose of matrix , same

tb <- t(b) cbind(rownum = c(col(tb)), colnum = c(row(tb)), value = c(tb)) 

Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

Nuget pack csproj using nuspec -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -