R Matrices

Matrices in R are two-dimensional data structures that can hold elements of the same data type. They are useful for mathematical computations and data organization.

Key Topics

Matrix Creation

Matrices can be created using the matrix() function.

# Creating a matrix
my_matrix <- matrix(1:9, nrow = 3, ncol = 3)

print(my_matrix)

Output:

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

Code Explanation: The matrix() function creates a 3x3 matrix with elements from 1 to 9, arranged by columns.

Matrix Operations

You can perform arithmetic operations on matrices, such as addition, subtraction, and multiplication.

# Matrix addition
matrix1 <- matrix(1:4, nrow = 2)
matrix2 <- matrix(5:8, nrow = 2)
sum_matrix <- matrix1 + matrix2

print(sum_matrix)

Output:

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

Code Explanation: Matrices matrix1 and matrix2 are added element-wise to produce sum_matrix.

Key Takeaways

  • Matrices are two-dimensional arrays with elements of the same data type.
  • The matrix() function is used to create matrices.
  • Arithmetic operations on matrices are performed element-wise.