# how to reshape the data.frame from a square matrix to three column

#### guozihuaa

##### New Member
I have a data.frame like this:
row.name a b c
1 1 4 7
2 2 5 8
3 3 6 9
and I want to reshape it like this
rownamesnames1 names2 weight
1 a a 1
2 b a 2
3 c a 3
4 a b 4
5 b b 5
6 c b 6
7 a c 7
8 b c 8
9 c c 9
is there is a efficient way to do this?
this is my code:
mydf<-data.frame(a=c(1,2,3),b=c(4,5,6),c=c(7,8,9))
row.names(mydf)<-c("a","b","c")

names1<-rep(c("a","b","c"),3)
names2<-rep(c("a","b","c"),each=3)
df2<-as.matrix(data.frame(names1,names2))
weight<-apply(df2,1,function(x){mydf[x[1],x[2]]})
newdf<-data.frame(names1,names2,weight)

I think it is too ugly. Is there a function or package that I can solve this question directly. Thank you very much

#### trinker

##### ggplot2orBust
I just added this function to ma package I maintain on GitHub called qdapTools (will be pushed to CRAN eventually):

Code:
library(devtools)
install_github("trinker/qdapTools")
library(qdapTools)

matrix2long(mydf, "names2", "names1", "weight")[, c(2, 1, 3)]
Code:
  names1 names2 weight
1      a      a      1
2      b      a      2
3      c      a      3
4      a      b      4
5      b      b      5
6      c      b      6
7      a      c      7
8      b      c      8
9      c      c      9

Or all in base R:

Code:
data.frame(
names1 = rep(colnames(mydf), nrow(mydf)),
names2 =  rep(rownames(mydf), each = ncol(mydf)),
weight = unlist(mydf)
)
which is what matrix2long does.

#### guozihuaa

##### New Member
I just added this function to ma package I maintain on GitHub called qdapTools (will be pushed to CRAN eventually):

Code:
library(devtools)
install_github("trinker/qdapTools")
library(qdapTools)

matrix2long(mydf, "names2", "names1", "weight")[, c(2, 1, 3)]
Code:
  names1 names2 weight
1      a      a      1
2      b      a      2
3      c      a      3
4      a      b      4
5      b      b      5
6      c      b      6
7      a      c      7
8      b      c      8
9      c      c      9

Or all in base R:

Code:
data.frame(
names1 = rep(colnames(mydf), nrow(mydf)),
names2 =  rep(rownames(mydf), each = ncol(mydf)),
weight = unlist(mydf)
)
which is what matrix2long does.
Thank you very much for your excellent response!