向量化矩阵
我有一个 1000 x 1000 的大型二维矩阵。我想对其进行整形,使其成为一列(或行)。例如,如果矩阵是:
A B C
1 4 7
2 5 8
3 6 9
我想把它变成:
1 2 3 4 5 6 7 8 9
我不需要保留列标题,只需保留数据的顺序。如何使用 reshape2
(这是我认为最容易使用的包)来执行此操作?
为了澄清起见,我提到了reshape
,因为我认为这是实现此目的的最佳方法。我可以看到有一些更简单的方法,我对此非常满意。
I have a large 2D matrix that is 1000 x 1000. I want to reshape this so that it is one column (or row). For example, if the matrix was:
A B C
1 4 7
2 5 8
3 6 9
I want to turn it in to:
1 2 3 4 5 6 7 8 9
I do not need to preserve the column headers, just the order of the data. How do I do this using reshape2
(which is the package that I presumed was the easiest to use)?
Just to clarify, I mentioned reshape
as I thought it was the best way of doing this. I can see that there are simpler methods which I am perfectly happy with.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为很难找到比以下更紧凑的方法:
但是,如果您想保留矩阵结构,那么对 dim 属性的这种重新设计将是有效的:
将会有更紧凑的方法来获取维度的乘积但上述方法强调了dim属性是矩阵的二元素向量。在该示例中获取“9”的其他方法包括:
I think it will be difficult to find a more compact method than:
However, if you want to retain a matrix structure, then this reworking of the dim attribute would be be effective:
There would be more compact methods of getting the product of the dimensions but the above method emphasizes that the dim attribute is a two element vector for matrices. Other ways of getting the "9" in that example include:
一个可能的解决方案,但不使用 reshape2:
A possible solution, but without using reshape2:
来吧,R 伙计们,让我们给 OP 一个 reshape2 解决方案:
我只是懒得去测试它比 c(m) 慢多少。不过,它是一样的:
[编辑:哦,我在跟谁开玩笑:]
Come on R guys, lets give the OP a reshape2 solution:
I just cant be bothered to test how much slower it is than c(m). It is the same, though:
[EDIT: oh heck who am I kidding:]
as.vector(m) 应该比 c(m) 更有效:
as.vector(m) should be little more efficient then c(m):
一种更简单的方法是使用函数“sapply”(或者也可以使用“for”循环来完成相同的操作)
One more simple way to do it by using function "sapply" (or the same could be done with 'for' loop as well)