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.
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.
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.
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With