[英]R matrix to rownames colnames values
I have a matrix A which I want to convert into a data.frame of the form: 我有一个矩阵A,我想将其转换为表格的data.frame:
rownames colnames values
Using 运用
unlist(A)
helps but does not give me the rownames 帮助但不给我rownames
Thank you for your help. 谢谢您的帮助。
You could use the reshape2-package: 你可以使用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: 基础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
:
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: 甚至更短,使用
expand.grid
并确保命名输入:
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
或者甚至更短,使用
as.data.frame.table
(将提供大部分结果),并使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.