从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
显然嵌套循环是可行的,但是我知道有很多不错的工具可以用于重塑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屋!
查看全文