Matrices
In this lesson, we will discuss matrices.
We'll cover the following...
Matrices are R objects where elements are arranged in a two-dimensional rectangular layout.
Like arrays, they contain elements of the same data type.
Creating Matrices
A Matrix is created using the matrix() function. The matrix() function takes an atomic vector as input. We can also define how many rows should be in the matrix by setting the nrow argument to a number. Furthermore, we can also set the ncol argument, which tells R how many columns to include in the matrix.
Why Do We Need Matrices If We Have Arrays?
Matrices in R language are only dimensional. A matrix is just a more convenient constructor. There are many functions and methods especially mathematical and statistical methods that only accept 2D arrays. So, to ensure that the programmer does not make the mistake of making the 2D array an nD array, a convenient object specifically for this task matrix is used.
Syntax
matrix(data, nrow, ncol, byrow, dimnames)
Here, data is the input vector, nrow is the number of rows to be created, ncol is the number of columns to be created, byrow is a logical clue: which if set to TRUE arranges elements row-wise and dimnames is the parameter that lets us assign names to the rows and columns.
Let’s have a look at the code to create an empty matrix:
Let’s use a populated vector to create a matrix:
Let’s play around with the matrix() function.
We can also set the names of rows and columns. In the following code snippet, we name rows from r1...r4 and name columns from c1...c3.
Accessing and Manipulating Matrices
Elements of a matrix can be accessed and updated by using the row and column index of the element inside square brackets [].
Changing the value of an element in a matrix can be done by first accessing the element using square brackets and then assigning it a different value or by using the column-wise single index.