79

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.

4
  • 11
    I don't understand the downvotes. I am aware that this is a beginner-level question, but I thought that these are accepted here. Googling the question did not find an answer because practically all results were people asking how to do the opposite (turn a matrix into a vector). Could somebody please explain what is wrong with the question?
    – rumtscho
    Jan 30, 2013 at 23:14
  • Probably because when I Google "create matrix in R" nearly every result points you to the function matrix. (Gavin's solution is less discoverable, though.)
    – joran
    Jan 30, 2013 at 23:22
  • 3
    @joran I wasn't googling "create matrix", I was googling "convert vector to matrix" and "turn vector to matrix". One has to know that creating a new matrix can take a vector as an argument in order to come up with the idea to search for "create", which makes it something of a chicken-and-egg problem :( But thank you for explaining.
    – rumtscho
    Jan 30, 2013 at 23:26
  • 3
    The very first result when I Google "convert a vector to matrix in R" is this which tells you to use matrix.
    – joran
    Jan 30, 2013 at 23:29

2 Answers 2

89

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.

1
  • Question: does this internally create a new object?
    – pglpm
    Oct 22, 2022 at 9:42
52

A matrix is really just a vector with a dim attribute (for the dimensions). So you can add dimensions to vec using the dim() function and vec will then be a matrix:

vec <- 1:49
dim(vec) <- c(7, 7)  ## (rows, cols)
vec

> vec <- 1:49
> dim(vec) <- c(7, 7)  ## (rows, cols)
> vec
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    8   15   22   29   36   43
[2,]    2    9   16   23   30   37   44
[3,]    3   10   17   24   31   38   45
[4,]    4   11   18   25   32   39   46
[5,]    5   12   19   26   33   40   47
[6,]    6   13   20   27   34   41   48
[7,]    7   14   21   28   35   42   49
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.