如何在R中将向量转换为矩阵? [英] How to turn a vector into a matrix in R?
问题描述
我有一个包含 49 个数值的向量.我想要一个 7x7 的数字矩阵.
I have a vector with 49 numeric values. I want to have a 7x7 numeric matrix instead.
是否有某种方便的自动转换语句可以使用,或者我是否必须将正确的向量子集的 7 个单独列分配给新矩阵?我希望有类似于 c(myMatrix)
的对立面,当然可以选择提供我想要的行数和/或列数.
Is there some sort of convenient automatic conversion statement I can use, or do I have to do 7 separate column assignments of the correct vector subsets to a new matrix? I hope that there is something like the oposite of c(myMatrix)
, with the option of giving the number of rows and/or columns I want to have, of course.
推荐答案
只需使用matrix
:
matrix(vec,nrow = 7,ncol = 7)
使用 matrix
而不是像 Gavin 指出的那样简单地改变维度属性的一个优点是,您可以使用 byrow
指定矩阵是按行填充还是按列填充> matrix
中的参数.
One advantage of using matrix
rather than simply altering the dimension attribute as Gavin points out, is that you can specify whether the matrix is filled by row or column using the byrow
argument in matrix
.
这篇关于如何在R中将向量转换为矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!