从 n x m 矩阵转换为 R 中的长矩阵 [英] Convert from n x m matrix to long matrix in R
本文介绍了从 n x m 矩阵转换为 R 中的长矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
注意:这不是图形问题.
Note: This is not a graph question.
我有一个 n x m 矩阵:
I have an n x m matrix:
> m = matrix(1:6,2,3)
> m
a b c
d 1 2 3
e 4 5 6
我想将其转换为长矩阵:
I would like to convert this to a long matrix:
> m.l
a d 1
a e 4
b d 2
b e 5
c d 3
c e 6
显然嵌套 for 循环可以工作,但我知道有很多很好的工具可以在 R 中重塑矩阵.到目前为止,我只找到了关于从长矩阵或宽矩阵转换为 nxm 矩阵的文献,而不是相反的方法.我错过了一些明显的东西吗?我该如何进行这种转换?
Obviously nested for loops would work but I know there are a lot of nice tools for reshaping matrixes in R. So far, I have only found literature on converting from long or wide matrixes to an n x m matrix and not the other way around. Am I missing something obvious? How can I do this conversion?
谢谢!
推荐答案
如果你需要单列矩阵
matrix(m, dimnames=list(t(outer(colnames(m), rownames(m), FUN=paste)), NULL))
# [,1]
#a d 1
#a e 4
#b d 2
#b e 5
#c d 3
#c e 6
对于 data.frame 输出,您可以使用 reshape2
For a data.frame output, you can use melt
from reshape2
library(reshape2)
melt(m)
这篇关于从 n x m 矩阵转换为 R 中的长矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文