A matrix
is simply a set of numbers arranged in rows
and columns
to form a rectangular array. The numbers inside a matrix are called the elements, or entries, of the matrix.
The matrix()
function in R
is used to create a matrix.
In this shot, we’ll learn how to use the matrix()
function to create matrices in R
.
matrix(data, nrow, ncol, byrow, dimnames)
Parameter | Description |
data | The input vector that becomes the data elements of the matrix; required. |
nrow | The desired number of rows; required. |
ncol | Tthe most desired number of columns. |
byrow | An optional, logical value that is ``FALSE`` by default and so the matrix is filled by columns. If otherwise, the matrix is filled by rows. |
dimnames | An optional attribute for the matrix of length two(``2``) that gives the respective names of the rows and columns of the matrix. |
Let us create a matrix and use the matrix()
function.
# using the matrix() function to create a matrixmymatrix <- matrix(c(1,2,3,4,5,6), #datanrow = 2, # number of rowsncol = 2, # number of columnsbyrow = FALSE, # matrix fillingdimname = list(c("row1", "row2"),c("Col1", "Col2")) # names of rows and columns)# printing the matrixmymatrix
In the program above, we create a matrix, mymatrix
, in which we use the matrix()
function and its various parameter values to make the mymatrix
become a 2 × 2
matrix (i.e. 2 rows and 2 columns matrix) and also with their dimension names (row1
, row2
, col1
, col2
).
Note that the
c()
function is used to concatenate items together.
In this example, we create a matrix with strings.
#using the matrix() function to create a matrix of stringsmymatrix <- matrix(c("America", "China", "Jamaica","Turkey", "Sweeden", "Brazil"), # datanrow = 3, # number of rowsncol = 2 #number of columns)# printing the matrixmymatrix
In this shot, we’eve created a matrix, mymatrix
, that has string elements, and use the various parameter values to make the matrix a 3 × 2
matrix.