Sunday 14 January 2018

Introduction to R - Part 3 : Matrices

Introduction to Matrix



In my previous post We spoke about Vectors. Today we are going to talk about Matrices.

I get reminded of the movie Matrix. Well I think we can relate R Matrix to the movie Matrix. When I first started watching the Matrix movie , I was clueless and it did not make sense at all. I think it was the case for most fans. But then I watched it couple of times and I finally managed to understand what it was about.

R- Matrix might be a similar experience for you. Once you start playing with it you get the hang of it.



What is a Matrix ?? 

Well it's like the brother of the Vector. A vector is a one Dimensional structure. Where as a Matrix is a 2 Dimensional structure arranged into a fixed number of Rows and Columns.

Lets look at the syntax of creating a matrix.

> m <- matrix(1:6, byrow =TRUE, nrow = 2)
> m
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
> m <- matrix(1:6, nrow = 2)
> m
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

Notebyrow =TRUE means the data arranged row wise first.

Same way you can define a matrix and specify it column wise.

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

Matrix Recycling



You can also define a matrix specifying the number rows and columns

> matrix(1:3,nrow= 2, ncol = 3)
      [,1] [,2] [,3]
[1,]    1    3    2
[2,]    2    1    3

Here as you can see even though the range has 3 elements the matrix will repeat it to automatically recycle it.



When you want to put a 4-element vector in a 6-element matrix, R generates a warning.

> matrix(1:4,nrow = 2, ncol = 3)
     [,1] [,2] [,3]
[1,]    1    3    1
[2,]    2    4    2
Warning message:
In matrix(1:4, nrow = 2, ncol = 3) :
  data length [4] is not a sub-multiple or multiple of the number of columns [3]


Apart from the Matrix() function there is a more easy way to create matrices using cbind() or rbind()

cbind aka Column bind
> cbind(1:3,4:6)
       [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6

cbind() function adds columns to the matrix

rbind aka Row bind
> rbind(1:3,4:6)
     [,1] [,2] [,3]
[1,]    1    2    3

[2,]    4    5    6

rbind() function adds rows to the matrix

These functions can be used to add a row or a column to an existing matrix.

Lets first look at our matrix
> m
      [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6

Now lets add a new row with values 7 to 9
> rbind(m,7:9)
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9

Now lets add a new column with values 10 and 11.
> cbind(m,c(10:11))
       [,1] [,2] [,3] [,4]
[1,]    1    2    3   10
[2,]    4    5    6   11

Naming a Matrix
 In the case of vectors remember we used the names() function to name the elements. For matrix we can use the functions rownames() and colnames()

rownames() 

> rownames(m) <- c("Row1","Row2")
> m
          [,1] [,2] [,3]
Row1    1    2    3
Row2    4    5    6

colnames()

> colnames(m) <- c("Col1","Col2","Col3")
> m
        Col1 Col2 Col3
Row1    1    2    3
Row2    4    5    6

You can also name the rows and columns at the time of defining the vector using the "dimnames" attribute.

> matrix_with_names <- matrix(1:6,byrow = TRUE , nrow=2 , dimnames = list(c("Row1","ROw2"),c("Col1","Col2","Col3")))
> matrix_with_names
        Col1 Col2 Col3
Row1     1    2    3
ROw2    4    5    6

Coercion

As I explained in the beginning of this post Matrix is an extension of the Vector. Which means a matrix can hold only a single atomic vector type. But what happens when we try to mix it with different types. That's when coercion happens.

Let's create 2 matrices. Numeric and a character matrices.

> numeric_matrix <- matrix(1:8,ncol = 2)
> numeric_matrix
     [,1] [,2]
[1,]    1    5
[2,]    2    6
[3,]    3    7
[4,]    4    8

> character_matrix <- matrix(LETTERS[1:6], nrow = 4, ncol = 3)
> character_matrix
     [,1] [,2] [,3]
[1,] "A"  "E"  "C"
[2,] "B"  "F"  "D"
[3,] "C"  "A"  "E"
[4,] "D"  "B"  "F"

Now lets try bind these 2 together.
> cbind(numeric_matrix,character_matrix)
      [,1]  [,2]  [,3]  [,4]   [,5]
[1,] "1"  "5"  "A"  "E"  "C"
[2,] "2"  "6"  "B"  "F"  "D"
[3,] "3"  "7"  "C"  "A"  "E"
[4,] "4"  "8"  "D"  "B"  "F"

As you can see the numeric elements were converted to characters.

To have multi dimensional matrices you will need to use lists or frames which I will cover later.

Matrix Sub-setting

Matrix sub setting works the same way as Vectors. However since Matrix is a 2D structure you need  to define rows and columns for sub setting.

> m <- matrix(1:9, byrow =TRUE, nrow = 3)
> m
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9

Let's use this matrix of for our examples.

Let's see how we can select 3rd element of the 1st Row.
> m[1,3]
[1] 3

You can just specify the Row and leave the column blank to get all elements of a particular Row.
> m[1,]
[1] 1 2 3

You can just specify the Column and leave the Row blank to get all elements of a particular Column.
> m[,3]
[1] 3 6 9

So what happens if we just set 1 number.
Eg:  > m[4]
[1] 2
It counts the 4th element in the matrix by going through rows first and then columns and gives the output.

So if we say > m[8] you should get 6 as the output.

> m[2,c(2,3)]
[1] 5 6

In this example the output gives the 2nd and 3rd elements of the 2nd row.

> m[c(1,2),c(2,3)]
     [,1] [,2]
[1,]    2    3
[2,]    5    6

This example gives 2nd and 3rd elements of Row 1 and 2.

Note: The same way we used names in vectors we can use the same way to sub set the matrices.
You can use the combination of both index and name.

Logical vectors work the same way. The elements which has True will be selected.

Matrix Arithmetic's

Matrix arithmetic's also work the same way as Vectors. Only difference is you can do an operation using 2 matrices. For an example when you multiply a matrix with another matrix the multiplication will be done element wise. If the number of elements do not match in both matrices Recycling will be performed by R.

Alright that's the basics on Matrices. Well it wont be easy to meet Neo (Keenu Reeves) from the Matrix Film yet.



As you need to practise more to face the Matrix revolution.






No comments:

Post a Comment

Blog Archive