\(~~~~~~\)Data Structure in R: Matrix\(~~~~~~\)

Somsak Chanaim

International College of Digital Innovation, CMU

October 30, 2024

Data Stuctures

Data Stucture in R (ref: First Steps in R)

Matrix

In R, matrices are two-dimensional, rectangular data structures.

They can only contain elements of a single data type (e.g., all numeric, all character, etc.).

How the create the matrix

Create a matrix object using the matrix() function.

\[mat.A = \begin{bmatrix} 1&2&3&4\end{bmatrix}\]

\[mat.B = \begin{bmatrix} 1\\2\\3\\4\end{bmatrix}\]

\[mat.C = \begin{bmatrix} 1&3\\2&4\end{bmatrix}\]

\[mat.D = \begin{bmatrix} 1&2\\3&4\end{bmatrix}\]

The matrix in R is not the same as the matrix in linear algebra because of the multiplication and division operations.

\[mat.C\times mat.D = \begin{bmatrix} 1&3\\2&4\end{bmatrix} \times \begin{bmatrix} 1&2\\3&4\end{bmatrix}=\begin{bmatrix} 10&14\\14&20\end{bmatrix}\]

The multiplication operation uses the %*% function

Matrix transpose

We can compute the matrix transpose using the t() function

\[mat.A^T = \begin{bmatrix} 1&2&3&4\end{bmatrix}^T=\begin{bmatrix} 1\\2\\3\\4\end{bmatrix}\]

\[mat.B^T = \begin{bmatrix} 1\\2\\3\\4\end{bmatrix}^T=\begin{bmatrix} 1&2&3&4\end{bmatrix}\]

\[mat.C^T = \begin{bmatrix} 1&3\\2&4\end{bmatrix}^T=\begin{bmatrix} 1&2\\3&4\end{bmatrix}\]

\[mat.D^T = \begin{bmatrix} 1&2\\3&4\end{bmatrix}^T=\begin{bmatrix} 1&3\\2&4\end{bmatrix}\]

Matrix determinant

We use the det() function. (For square matrix only)

\[\begin{aligned} det(mat.C) &= det\left(\begin{bmatrix} 1&3\\2&4\end{bmatrix}\right)\\&=(1\times 4)-(2\times 3) \\&= -2\end{aligned}\]

\[\begin{aligned}det(mat.D) &= det\left(\begin{bmatrix} 1&2\\3&4\end{bmatrix}\right)\\&=(1\times 4)-(3\times 2) \\&= -2 \end{aligned}\]

Matrix inverse

We use the solve() function. (For square matrix only)

\[\begin{aligned}mat.C^{-1}&=\dfrac{1}{det(mat.C)}\begin{bmatrix} 4&-3\\-2&1\end{bmatrix}\\&=\dfrac{1}{-2}\begin{bmatrix} 4&-3\\-2&1\end{bmatrix}\\&=\begin{bmatrix} -2&1.5\\1&-0.5\end{bmatrix}\end{aligned}\]

\[\begin{aligned}mat.D^{-1}&=\dfrac{1}{det(mat.D)}\begin{bmatrix} 4&-2\\-3&1\end{bmatrix}\\&=\dfrac{1}{-2}\begin{bmatrix} 4&-3\\-2&1\end{bmatrix}\\&=\begin{bmatrix} -2&1\\1.5&-0.5\end{bmatrix}\end{aligned}\]

Solve the linear equation system \(Ax=B\)

Let

\[A=\begin{bmatrix}1&3\\2&4\end{bmatrix},~x=\begin{bmatrix}x_1\\x_2\end{bmatrix},~B=\begin{bmatrix}5\\13\end{bmatrix} \]

We can solve the linear equation system with the solve() function too. \[\begin{align*} Ax&=B\\ \begin{bmatrix}1&3\\2&4\end{bmatrix}\begin{bmatrix} x_1\\x_2\end{bmatrix}&=\begin{bmatrix} 5\\13\end{bmatrix} \end{align*}\]

How to access/edit the matrix

\[mat.E = \begin{bmatrix} 1&2&3\\3&4&6\\7&8&9\end{bmatrix}\]

1. Access a specific element

To access the element at row 2, column 2 of a matrix mat.E

2. Access an entire row

To access the entire second row of mat.E

or

or

3. Access an entire column

To access the entire third column of mat.E

4. Access a submatrix

You can also create a submatrix by specifying the row and column indices. For example, to extract a 2x2 submatrix from mat.E

From the object mat.E, show the values in rows 1 and 3 only.

Don’t show row 2

From the object mat.E, show the values in rows 3 and 1 respectively.

Don’t show row 2 and col 2

or

6. Access using logical conditions

To access elements that satisfy a certain condition, for example, elements greater than 5

7. Assign values to specific elements

You can also assign new values to specific elements in the matrix. For example:

Assign the previous value to a object mat.E.

change the value inside matrix

change the mat.F at (1,1) and (2,2) to 5

or use the diag() function. (diag = diagonal)

From the object mat.F, change the values in the first row to 1 and 2 respectively.

Merging two matrices with the cbind() and rbind() functions.

\[A=\begin{bmatrix}1&3\\2&4\end{bmatrix}\]

\[B=\begin{bmatrix}5&7\\6&8\end{bmatrix}\]

cbind() function: Merge by column

\[\begin{bmatrix}A&B\end{bmatrix}=\begin{bmatrix}1&3&5&7\\2&4&6&8\end{bmatrix}\]

\[\begin{bmatrix}B&A\end{bmatrix}=\begin{bmatrix}5&7&1&3\\6&8&2&4\end{bmatrix}\]

rbind() function: Merge by row

\[\begin{bmatrix}A\\B\end{bmatrix}=\begin{bmatrix}1&3\\2&4\\5&7\\6&8\end{bmatrix}\]

\[\begin{bmatrix}B\\A\end{bmatrix}=\begin{bmatrix}5&7\\6&8\\1&3\\2&4\end{bmatrix}\]

Exercise: Matrix Part 1

1. Create a Matrix

  • Create a \((3 \times 3)\) matrix with the numbers 1 to 9, filled by rows. Assign the matrix to a variable named my_matrix.

Solution:

my_matrix <- matrix(1:9, nrow = 3, byrow = TRUE)

2. Access Matrix Elements

  • Access the element in the second row and third column of my_matrix.

Solution:

element <- my_matrix[2, 3]

3. Matrix Dimensions

  • Find the number of rows and columns in my_matrix.

  • Hint, use dim() function.

Solution:

dims <- dim(my_matrix)

4. Matrix Addition

  • Create another \((3 \times 3)\) matrix my_matrix2 with values 9 to 1 (filled by rows). Add my_matrix and my_matrix2 together.

Solution:

my_matrix2 <- matrix(9:1, nrow = 3, byrow = TRUE)
result_matrix <- my_matrix + my_matrix2

5. Matrix Multiplication

  • Perform matrix multiplication between my_matrix and my_matrix2.

Solution:

product_matrix <- my_matrix %*% my_matrix2

6. Transpose a Matrix

  • Find the transpose of my_matrix.

Solution:

transposed_matrix <- t(my_matrix)

7. Matrix Determinant

  • Calculate the determinant of a \((2 \times 2)\) matrix my_matrix3 with values 4, 7, 2, and 6.

Solution:

my_matrix3 <- matrix(c(4, 7, 2, 6), nrow = 2)
det_value <- det(my_matrix3)

8. Inverse of a Matrix

  • Find the inverse of my_matrix3, if it exists.

Solution:

inverse_matrix <- solve(my_matrix3)

9. Diagonal of a Matrix

  • Extract the diagonal elements of my_matrix.

Solution:

diagonal_elements <- diag(my_matrix)

10. Create an Identity Matrix

  • Create a \((4 \times 4)\) identity matrix.

Solution:

   identity_matrix <- diag(4)

Exercise: Matrix part 2

The exercises 11 to 20 focusing on data manipulation with matrix objects in R:

11. Element-wise Multiplication

  • Perform element-wise multiplication between my_matrix and a matrix of the same dimensions containing all 2’s.

Solution:

   result_matrix <- my_matrix * matrix(2, nrow = 3, ncol = 3)

12. Row and Column Sums

  • Calculate the sum of each row and each column in my_matrix.

  • Hints, use rowSum() and colSums functions.

Solution:

   row_sums <- rowSums(my_matrix)
   col_sums <- colSums(my_matrix)

13. Add a Row to a Matrix

  • Add a new row c(10, 11, 12) to my_matrix and create a new matrix my_matrix_extended.

Solution:

   new_row <- c(10, 11, 12)
   my_matrix_extended <- rbind(my_matrix, new_row)

14. Add a Column to a Matrix

  • Add a new column c(13, 14, 15, 16) to my_matrix_extended.

Solution:

   new_column <- c(13, 14, 15, 16)
   my_matrix_extended <- cbind(my_matrix_extended, new_column)

15. Subsetting a Matrix

  • Extract a submatrix from my_matrix that includes the first two rows and the last two columns.

Solution:

   sub_matrix <- my_matrix[1:2, 2:3]

16. Replace Elements in a Matrix

  • Replace all elements in my_matrix that are greater than 5 with the value 0.

Solution:

   my_matrix[my_matrix > 5] <- 0

17. Matrix Mean

  • Calculate the mean of all the elements in my_matrix.

Solution:

   matrix_mean <- mean(my_matrix)

18. Apply a Function to Rows or Columns

  • Use the apply() function to calculate the product of each row in my_matrix.

Solution:

   row_products <- apply(my_matrix, 1, prod)

19. Matrix to Vector

  • Convert my_matrix into a vector.

  • Hint, use as.vector() function.

Solution:

   matrix_vector <- as.vector(my_matrix)

20. Reshape a Matrix

  • Reshape my_matrix into a \((1 \times 9)\) matrix.

Solution:

   reshaped_matrix <- matrix(my_matrix, nrow = 1)