I have a matrix A which I want to convert into a data.frame of the form:
rownames colnames values
Using
unlist(A)
helps but does not give me the rownames
Thank you for your help.
You could use the reshape2-package:
# load package
> require(reshape2)
# create an example matrix
> mdat <- matrix(c(1,2,3, 11,12,13), nrow = 2, ncol=3, byrow=TRUE,
+ dimnames = list(c("row1", "row2"),
+ c("C.1", "C.2", "C.3")))
> mdat
C.1 C.2 C.3
row1 1 2 3
row2 11 12 13
# bring matrix to long format using melt()
> melt(mdat)
Var1 Var2 value
1 row1 C.1 1
2 row2 C.1 11
3 row1 C.2 2
4 row2 C.2 12
5 row1 C.3 3
6 row2 C.3 13
Solution in base R:
Here's a matrix:
test <- matrix(1:9,nrow=3)
rownames(test) <- letters[1:3]
colnames(test) <- letters[4:6]
> test
d e f
a 1 4 7
b 2 5 8
c 3 6 9
Convert to a data.frame
as required:
data.frame(
rownames=as.vector(row(test,as.factor=TRUE)),
colnames=as.vector(col(test,as.factor=TRUE)),
values=as.vector(test)
)
Or even shorter, using expand.grid
and making sure to name the inputs:
data.frame(
expand.grid(rownames=rownames(test),colnames=colnames(test)),
values=as.vector(test)
)
Or even shorter again, using as.data.frame.table
(which will give the majority of the result), and setting the names using setNames
setNames(as.data.frame.table(test),c("rownames","colnames","values"))
Result:
rownames colnames values
1 a d 1
2 b d 2
3 c d 3
4 a e 4
5 b e 5
6 c e 6
7 a f 7
8 b f 8
9 c f 9