R - convert matrix wide to long format with as.table() or melt()

03 Jun 2018

Two ways to convert a matrix from wide to long format:

# Way 1: convert matrix (wide format) into long format (Var1 Var2 Freq)
as.data.frame(as.table(matrix))

# Way 2: using reshape2::melt
library(reshape2)
colnames(mymatrix) <- rownames(mymatrix) <- 1:ncol(mymatrix)
mymatrixLong <- melt(mymatrix)
[ R  function  matrix  data_frame  ]