Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn a vector into a matrix in R?

Tags:

r

vector

matrix

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.

like image 537
rumtscho Avatar asked Jan 30 '13 22:01

rumtscho


People also ask

How do I convert data into a matrix in R?

Convert a Data Frame into a Numeric Matrix in R Programming – data. matrix() Function. data. matrix() function in R Language is used to create a matrix by converting all the values of a Data Frame into numeric mode and then binding them as a matrix.

Can we define matrix from a vector in R?

A vector can be created by using c() function. Vectors in R are the same as the arrays in C language which are used to hold multiple data values of the same type. Vectors can also be used to create matrices. Matrices can be created with the help of Vectors by using pre-defined functions in R Programming Language.


2 Answers

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.

like image 173
joran Avatar answered Oct 05 '22 20:10

joran


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 
like image 25
Gavin Simpson Avatar answered Oct 05 '22 20:10

Gavin Simpson