Chapter 10 Matrices in R

10.1 What are Matrices?

Matrices are two-dimensional data structures in R and are arranged in a rectangular layout. Matrices can contain only one data type. We can create matrices of any of the six data types we discussed before. A matrix can also be thought of as a vector in two dimension.

We can usematrix function to create a matrix in R programming. I will suggest using “? matrix” for detailed documentation of matrix function Lets create a matrix with 3 rows and two columns

matrix(1:6,nrow = 3,ncol = 2)
##      [,1] [,2]
## [1,]    1    4
## [2,]    2    5
## [3,]    3    6

What if we don’t specify the number of rows and columns?

matrix(1:6,3,2)
##      [,1] [,2]
## [1,]    1    4
## [2,]    2    5
## [3,]    3    6

As you have guessed from the above output, R will automatically pick the number of rows and columns based on the order of input. Let’s specify one of the dimension (either col or row) and see the output:-

matrix(1:6,ncol=3)
##      [,1] [,2] [,3]
## [1,]    1    3    5
## [2,]    2    4    6

So far we have not assigned any columnname and rowname to matrix. Lets create a matrix M and assign colnames and

M<-matrix(1:20,ncol=4)
colnames(M)<-c("A","B","C","D")
rownames(M)<-c("E","F","G","H","I")

Lets check the Matrix “M”

M
##   A  B  C  D
## E 1  6 11 16
## F 2  7 12 17
## G 3  8 13 18
## H 4  9 14 19
## I 5 10 15 20

As you can see from the output, we have successfully assigned names to the colnames we can also call the specific columns now. For example Matrix[rowname,colname] will call the required row and columns by name.

M["F","D"]
## [1] 17

We can row name field blank in the Matrix[rowname,colname] to call complete column

M[,"D"]
##  E  F  G  H  I 
## 16 17 18 19 20

As you can see in the above example we have kept the row blank. This will cause the above expression to pick all the values to the corresponding columns We can also access specific elements of vectors by specifying row number and column number Lets say we want to pick specific column and vector from Matrix, say 2nd row and 3rd column

M[2,3]
## [1] 12

10.2 Extracting Row/Column from Matrices

We can also extract more than one row/column at a time. For example below we extraacted first and third column and second row.

M[2,c(1,3)]
##  A  C 
##  2 12

So what else can we do with Matrices?

10.3 Operations in Matrices

Let perform some operations in Matrices Let’s create two Matrices M1 and M2 and perform some operations

M1<- matrix(1:15,nrow=5)
M1
##      [,1] [,2] [,3]
## [1,]    1    6   11
## [2,]    2    7   12
## [3,]    3    8   13
## [4,]    4    9   14
## [5,]    5   10   15
M2<- matrix(1:15,nrow=5)
M2
##      [,1] [,2] [,3]
## [1,]    1    6   11
## [2,]    2    7   12
## [3,]    3    8   13
## [4,]    4    9   14
## [5,]    5   10   15

10.3.1 Arithmetic Operation in Matrices

What if we add two matrices? Matrices operations can be performed similar to how arithmetic operations are performed on numbers. However we should be careful with the dimension of the numbers that we are working on:-

Lets create three matrices M1, M2, M3 .

M1<- matrix(1:15,nrow=5)
M1
##      [,1] [,2] [,3]
## [1,]    1    6   11
## [2,]    2    7   12
## [3,]    3    8   13
## [4,]    4    9   14
## [5,]    5   10   15
M2<- matrix(2:16,nrow=5)
M2
##      [,1] [,2] [,3]
## [1,]    2    7   12
## [2,]    3    8   13
## [3,]    4    9   14
## [4,]    5   10   15
## [5,]    6   11   16
M3<-matrix(2:10,nrow=5)
## Warning in matrix(2:10, nrow = 5): data length [9] is not a sub-multiple or
## multiple of the number of rows [5]
M3
##      [,1] [,2]
## [1,]    2    7
## [2,]    3    8
## [3,]    4    9
## [4,]    5   10
## [5,]    6    2

Arithmetic Operations in Matrices

Additon Operation on Matrices of same dimension

M1+M2
##      [,1] [,2] [,3]
## [1,]    3   13   23
## [2,]    5   15   25
## [3,]    7   17   27
## [4,]    9   19   29
## [5,]   11   21   31

What if want to add Matrices of different dimensions? We can check dimension of Matrices using dim function

dim(M1)
## [1] 5 3
dim(M3)
## [1] 5 2

Multiplying Matrices of same dimension The following operation using “*" is element wise:-

M1*M2
##      [,1] [,2] [,3]
## [1,]    2   42  132
## [2,]    6   56  156
## [3,]   12   72  182
## [4,]   20   90  210
## [5,]   30  110  240

What if we want Matrix Multiplication? As an exercise try M1%*%M2 in R console for matrix multiplication and check the result. Once you run the operation you must have got an error message “Error in M1 %*% M2: non-conformable arguments" Why is it so? As a basic rule for matrix multiplication number of rows of Matrix1 should be equal to number of columns in Matrix2 when multiplying Matrix1 with Matrix2. You can check following link mathisfun

M4<- matrix(1:9,nrow=3)
M5<-matrix(10:18,nrow=3)
M4
##      [,1] [,2] [,3]
## [1,]    1    4    7
## [2,]    2    5    8
## [3,]    3    6    9
M5
##      [,1] [,2] [,3]
## [1,]   10   13   16
## [2,]   11   14   17
## [3,]   12   15   18

Lets see result of Matrix Multiplication

M4<- matrix(1:9,nrow=3)
M5<-matrix(10:18,nrow=3)
M4%*%M5
##      [,1] [,2] [,3]
## [1,]  138  174  210
## [2,]  171  216  261
## [3,]  204  258  312

You can see the elementwise operation result in R.

M4*M5
##      [,1] [,2] [,3]
## [1,]   10   52  112
## [2,]   22   70  136
## [3,]   36   90  162
M1/M2
##           [,1]      [,2]      [,3]
## [1,] 0.5000000 0.8571429 0.9166667
## [2,] 0.6666667 0.8750000 0.9230769
## [3,] 0.7500000 0.8888889 0.9285714
## [4,] 0.8000000 0.9000000 0.9333333
## [5,] 0.8333333 0.9090909 0.9375000

What if one of the matrices’ row or column is shorter than the other? Will recycling occur?

As an exercise create a 3X3 matrices and add it to M1.

10.4 Transposing a Matrix

You may also want to transpose your data in R. This is used to interchange rows and columns i.e rows become columns and columns become rows in new transposed matrix For example: -

M3<-t(M1)
M3
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    2    3    4    5
## [2,]    6    7    8    9   10
## [3,]   11   12   13   14   15

As you can see from the output, the rows have become columns and the columns have become rows. This can also be used to reshape a DataFrame. We will cover DataFrame in next chapter.

10.5 Common Matrix Operations in R

Sum of rows in Matrix

rowSums(M1)
## [1] 18 21 24 27 30

Sum of columns in Matrix

colSums(M1)
## [1] 15 40 65

Mean of rows in Matrix

rowMeans(M1)
## [1]  6  7  8  9 10

10.6 Naming Matrix row and column

rownames(M4)<-c("A","B","C")
colnames(M4)<-c("D","E","F")
M4
##   D E F
## A 1 4 7
## B 2 5 8
## C 3 6 9

We can also extract specific elements of a Matrix by specifying row and columns

M4[3,] #Extracting third row from Matrix M4
## D E F 
## 3 6 9
M4[,3] #Extracting third column from Matrix M4
## A B C 
## 7 8 9
M4[2,3] #Extracting second row and third column element from Matrix M4
## [1] 8

For details on Matrix operation you can also install Matrix package from CRAN The Comprehensive R Archive Network