# R Programming language - R Matrix

In R programming language, a matrix is a two-dimensional array of values of the same data type. Matrices are similar to vectors, but they have rows and columns instead of just one dimension. Here are some examples of matrices in R:

mat1 <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3) mat2 <- matrix(c("apple", "banana", "orange", "grape", "pineapple", "watermelon"), nrow = 2, ncol = 3)Source:www.theitroad.com

In R, you can create a matrix using the `matrix()`

function, which takes a vector of values and the number of rows and columns as arguments. You can also create a matrix using the `cbind()`

and `rbind()`

functions, which combine vectors into a matrix by column or by row, respectively. Here are some examples:

mat1 <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3) mat2 <- cbind(c(1, 2), c(3, 4), c(5, 6)) # Creates a matrix by column mat3 <- rbind(c(1, 2, 3), c(4, 5, 6)) # Creates a matrix by row

You can access individual elements of a matrix using square bracket notation, with the row and column indices separated by a comma, like this:

mat1 <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3) print(mat1[1, 2]) # Output: 2

You can also access entire rows or columns of a matrix using square brackets, with the row or column index and a blank space, like this:

mat1 <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3) print(mat1[, 2]) # Output: 2 5

You can perform operations on matrices using vectorized functions, which operate on all elements of a matrix at once. Here are some examples:

mat1 <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3) mat2 <- matrix(c(7, 8, 9, 10, 11, 12), nrow = 2, ncol = 3) sum_mat <- mat1 + mat2 # Adds corresponding elements of the two matrices prod_mat <- mat1 * mat2 # Multiplies corresponding elements of the two matrices

Understanding how to work with matrices in R is important for many data manipulation and analysis tasks, especially when working with numerical data that can be organized in a grid-like structure.