How to turn a vector into a matrix in R?

rumtscho picture rumtscho · Jan 30, 2013 · Viewed 126.8k times · Source

I have a vector with 49 numeric values. I want to have a 7x7 numeric matrix instead.

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.

Answer

joran picture joran · Jan 30, 2013

Just use matrix:

matrix(vec,nrow = 7,ncol = 7)

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.