R Matrices Tutorial with Examples

In R, a matrix is a two-dimensional data structure that stores elements of the same type (numeric, character, or logical). Matrices are widely used in data analysis, statistics, and mathematical computations.

Each matrix has rows and columns, making it ideal for handling tabular data.

In this tutorial, we will cover:

Let’s explore each topic with examples!

1. What is a Matrix in R?

A matrix in R is a two-dimensional array that contains elements of the same type (numeric, character, or logical). Matrices are created using the matrix() function, and you can specify the number of rows and columns.

Example (Basic Matrix):

# Create a numeric matrix with 2 rows and 3 columns
mat <- matrix(1:6, nrow = 2, ncol = 3)
print(mat)

Output:

     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
  • The matrix has 2 rows and 3 columns filled with the numbers 1 to 6.

2. Creating a Matrix

The matrix() function is used to create matrices. You can define the number of rows and columns using the nrow and ncol arguments. Data is filled column-wise by default.

Example (Creating a Numeric Matrix):

# Create a matrix with 3 rows and 3 columns
mat <- matrix(1:9, nrow = 3, ncol = 3)
print(mat)

Output:

     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
  • The matrix is filled with the numbers from 1 to 9.

Example (Filling Row-Wise):

To fill the matrix row-wise, you can use the byrow = TRUE argument.

# Create a matrix with row-wise filling
mat <- matrix(1:9, nrow = 3, byrow = TRUE)
print(mat)

Output:

     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
  • The numbers are filled across rows, rather than down columns.

3. Accessing Matrix Elements

You can access elements of a matrix using square brackets [ ] and specifying the row and column indices.

Example (Accessing a Single Element):

# Access the element in the second row, third column
element <- mat[2, 3]
print(element)  # Outputs: 6

Example (Accessing a Row or Column):

# Access the second row
second_row <- mat[2, ]
print(second_row)  # Outputs: 4 5 6

# Access the third column
third_column <- mat[, 3]
print(third_column)  # Outputs: 3 6 9
  • Use [row, ] to access a row and [ ,column] to access a column.

4. Modifying Matrix Elements

You can modify elements of a matrix by assigning new values to specific indices.

Example:

# Modify the element in the first row, second column
mat[1, 2] <- 100
print(mat)

Output:

     [,1] [,2] [,3]
[1,]    1  100    3
[2,]    4    5    6
[3,]    7    8    9
  • The element at position [1, 2] is updated to 100.

5. Matrix Operations

Matrices allow you to perform various operations such as addition, subtraction, and multiplication element-wise.

Example (Element-wise Operations):

# Create two matrices
mat1 <- matrix(1:4, nrow = 2)
mat2 <- matrix(5:8, nrow = 2)

# Perform element-wise operations
sum_mat <- mat1 + mat2  # Addition
diff_mat <- mat1 - mat2  # Subtraction

print(sum_mat)  # Outputs a matrix with summed elements
print(diff_mat)  # Outputs a matrix with subtracted elements

Output (Addition):

     [,1] [,2]
[1,]    6    8
[2,]    8   10

Output (Subtraction):

     [,1] [,2]
[1,]   -4   -4
[2,]   -4   -4
  • The operations are applied element-wise between corresponding elements of the matrices.

6. Matrix Functions

nrow() and ncol()

You can use nrow() and ncol() to find the number of rows and columns in a matrix.

# Get the number of rows and columns
rows <- nrow(mat)
cols <- ncol(mat)
print(rows)  # Outputs: 3
print(cols)  # Outputs: 3

dim()

The dim() function returns both the number of rows and columns.

# Get the dimensions of the matrix
dimensions <- dim(mat)
print(dimensions)  # Outputs: 3 3

rownames() and colnames()

You can assign and retrieve row names and column names for a matrix.

# Set row names and column names
rownames(mat) <- c("Row1", "Row2", "Row3")
colnames(mat) <- c("Col1", "Col2", "Col3")

# Print the matrix with names
print(mat)

Output:

     Col1 Col2 Col3
Row1    1  100    3
Row2    4    5    6
Row3    7    8    9

7. Combining Matrices

You can combine matrices either by rows using rbind() or by columns using cbind().

Example (Combining by Rows):

# Combine two matrices by rows
mat1 <- matrix(1:4, nrow = 2)
mat2 <- matrix(5:8, nrow = 2)

combined_rows <- rbind(mat1, mat2)
print(combined_rows)

Output:

     [,1] [,2]
[1,]    1    3
[2,]    2    4
[3,]    5    7
[4,]    6    8

Example (Combining by Columns):

# Combine two matrices by columns
combined_cols <- cbind(mat1, mat2)
print(combined_cols)

Output:

     [,1] [,2] [,3] [,4]
[1,]    1    3    5    7
[2,]    2    4    6    8

8. Matrix Arithmetic

You can perform scalar multiplication and other arithmetic operations on matrices.

Example (Scalar Multiplication):

# Multiply the matrix by a scalar value
scaled_mat <- mat * 2
print(scaled_mat)

Output:

     Col1 Col2 Col3
Row1    2  200    6
Row2    8   10   12
Row3   14   16   18
  • Each element in the matrix is multiplied by 2.

9. Matrix Multiplication

Matrix multiplication is different from element-wise multiplication. You can perform matrix multiplication using the %*% operator.

Example (Matrix Multiplication):

# Matrix multiplication
mat1 <- matrix(1:6, nrow = 2)
mat2 <- matrix(7:12, nrow = 3)

product_mat <- mat1 %*% mat2
print(product_mat)

Output:

     [,1] [,2]
[1,]   58   64
[2,]   79   88
  • Matrix multiplication follows the mathematical rules of dot product, and the dimensions must be compatible (e.g., the number of columns in the first matrix must equal the number of rows in the second matrix).

10.

Applying Functions to a Matrix (apply())

The apply() function is used to apply a function across the rows or columns of a matrix.

Example (Sum of Rows and Columns):

# Sum the rows (MARGIN = 1)
row_sums <- apply(mat, MARGIN = 1, FUN = sum)
print(row_sums)

# Sum the columns (MARGIN = 2)
col_sums <- apply(mat, MARGIN = 2, FUN = sum)
print(col_sums)

Output (Row Sums):

Row1 Row2 Row3 
 104   15   24 

Output (Column Sums):

Col1 Col2 Col3 
  12  113   18 
  • The apply() function allows you to apply a function across rows or columns by specifying MARGIN = 1 for rows and MARGIN = 2 for columns.

Summary of Common Matrix Functions in R

Function Description
matrix() Creates a matrix.
nrow(), ncol() Returns the number of rows and columns in a matrix.
dim() Returns the dimensions of a matrix.
rownames(), colnames() Sets or gets row and column names of a matrix.
rbind(), cbind() Combines matrices by rows or columns.
%*% Matrix multiplication.
apply() Applies a function across rows or columns.

Conclusion

Matrices in R are powerful tools for working with tabular data and performing mathematical operations. In this tutorial, we covered:

  • Creating matrices using the matrix() function.
  • Accessing and modifying matrix elements.
  • Performing element-wise and matrix arithmetic.
  • Using functions like nrow(), ncol(), and apply() to manipulate matrices.
  • Combining matrices using rbind() and cbind().

By mastering matrices, you’ll be well-equipped to handle multi-dimensional data and perform advanced data analysis in R.

Related posts

R Factors Tutorial with Examples

R Vectors Tutorial with Examples

R Arrays Tutorial with Examples