Loading web-font TeX/Main/Regular
Skip to main content

R: Matrix Operations

Matrix manipulation in R are very useful in Linear Algebra. Below are list of common yet important functions in dealing operations with matrices:
  • Transpose - t;
  • Multiplication - %*%;
  • Determinant - det; and,
  • Inverse - solve, or ginv of MASS library
  • Eigenvalues and Eigenvectors - eigen
Consider these matrices, \left[\begin{array}{ccc}3&4&5\\2&1&3\\6&5&4\end{array}\right] and  \left[\begin{array}{ccc}6&7&5\\4&5&8\\7&6&6\end{array}\right]. In R, these would be,

dat1 <- c(3,4,5,2,1,3,6,5,4)
matrix1 <- matrix(dat1, nrow = 3, ncol = 3, byrow = TRUE)
matrix1
[,1] [,2] [,3]
[1,] 3 4 5
[2,] 2 1 3
[3,] 6 5 4
dat2 <- c(6,7,5,4,5,8,7,6,6)
matrix2 <- matrix(dat2, nrow = 3, ncol = 3, byrow = TRUE)
matrix2
[,1] [,2] [,3]
[1,] 6 7 5
[2,] 4 5 8
[3,] 7 6 6
view raw MatrixOp1.R hosted with ❤ by GitHub
Transposing these, simply use t

t(matrix1)
[,1] [,2] [,3]
[1,] 3 2 6
[2,] 4 1 5
[3,] 5 3 4
t(matrix2)
[,1] [,2] [,3]
[1,] 6 4 7
[2,] 7 5 6
[3,] 5 8 6
view raw MatrixOp2.R hosted with ❤ by GitHub
Multiplying these, would be

matrix1 %*% matrix2
[,1] [,2] [,3]
[1,] 69 71 77
[2,] 37 37 36
[3,] 84 91 94
view raw MatrixOp3.R hosted with ❤ by GitHub
For the determinant, we have

det(matrix1)
[1] 27
det(matrix2)
[1] 61
view raw MatrixOp4.R hosted with ❤ by GitHub
Taking the inverse of matrix1 is achieved by solve or ginv R functions. Note that ginv is in MASS package, and so we have

solve(matrix1)
[,1] [,2] [,3]
[1,] -0.4074074 0.3333333 0.25925926
[2,] 0.3703704 -0.6666667 0.03703704
[3,] 0.1481481 0.3333333 -0.18518519
library(MASS)
ginv(matrix1)
[,1] [,2] [,3]
[1,] -0.4074074 0.3333333 0.25925926
[2,] 0.3703704 -0.6666667 0.03703704
[3,] 0.1481481 0.3333333 -0.18518519
view raw MatrixOp5.R hosted with ❤ by GitHub
Finally, for eigenvalues and eigenvectors simply use eigen

eigen(matrix1)
$values
[1] 11.238947 -2.088872 -1.150075
$vectors
[,1] [,2] [,3]
[1,] -0.6017346 -0.3458537 -0.4307244
[2,] -0.3305706 -0.5288292 0.8445517
[3,] -0.7270754 0.7750644 -0.3181336
eigen(matrix2)
$values
[1] 18.020246+0.000000i -0.510123+1.767726i -0.510123-1.767726i
$vectors
[,1] [,2] [,3]
[1,] 0.5729619+0i -0.4414068-0.3843531i -0.4414068+0.3843531i
[2,] 0.5495930+0i 0.6888097+0.0000000i 0.6888097+0.0000000i
[3,] 0.6079985+0i -0.2537249+0.3443799i -0.2537249-0.3443799i
view raw MatrixOp6.R hosted with ❤ by GitHub
The output above returns the $values, which is the eigenvalues, and $vectors, the eigenvectors.