How to Perform Common Matrix Operations in R


R has built in support for matrices and also supports many of the common matrix operations that are found in linear algebra and optimization. In this article, we will learn how to perform common matrix operations in R.

We start with finding the transpose of a matrix. We can use the t() function to transpose a matrix in R.

v = c(1, 2, 3, 4, 5, 6)

mat = matrix(v, 2, 3)


Next, we can find the inverse using the solve function. The iverse of a matrix is used in many optimization algorithms.

v = c(1, 2, 3, 4, 5, 6)

mat = matrix(v, 2, 3)


Another built in operation is matrix multiplication. We can use the %*% operator on two matrices to multiply them.

v = c(1, 2, 3, 4, 5, 6)
a = c(1, 2, 3, 4, 5, 6)

v %*% a

Finaly, we can construct a diagonal matrix using the diag function. For example, we can easily create the indentiy matrix with this function.