0% found this document useful (0 votes)
19 views103 pages

Matrix Introduction: IIT Guwahati

The document provides an introduction to matrices, explaining their relationship with vectors and arrays, and how to create and manipulate them in R. It covers various operations, functions, and attributes associated with matrices, including how to fill them by rows or columns, perform arithmetic operations, and check their properties. Additionally, it illustrates the creation of numeric, integer, character, and logical matrices, as well as the use of functions like dim() and length() for matrix analysis.

Uploaded by

jyrfjidjjhstull
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views103 pages

Matrix Introduction: IIT Guwahati

The document provides an introduction to matrices, explaining their relationship with vectors and arrays, and how to create and manipulate them in R. It covers various operations, functions, and attributes associated with matrices, including how to fill them by rows or columns, perform arithmetic operations, and check their properties. Additionally, it illustrates the creation of numeric, integer, character, and logical matrices, as well as the use of functions like dim() and length() for matrix analysis.

Uploaded by

jyrfjidjjhstull
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 103

Matrix Introduction

IIT Guwahati

1/4
Vectors and Matrices
I In the previous module, we have learnt about vectors. An array is a
multi-dimensional extension of a vector. As a special case, if the
array has only two dimension, then such an array is also called a
matrix.

2/4
Vectors and Matrices
I In the previous module, we have learnt about vectors. An array is a
multi-dimensional extension of a vector. As a special case, if the
array has only two dimension, then such an array is also called a
matrix.

Figure 1: Relationship between vectors and matrices

2/4
Arrays and Matrices

I Arrays are based on atomic vectors, meaning that the elements


within an array must have the same basic type like numeric,
character and several others.

3/4
Arrays and Matrices

I Arrays are based on atomic vectors, meaning that the elements


within an array must have the same basic type like numeric,
character and several others.
I Matrix is a special type of array with two dimensions having data of
one type. We can find length of matrix which indicates the number of
elements in a matrix.

3/4
Arrays and Matrices

I Arrays are based on atomic vectors, meaning that the elements


within an array must have the same basic type like numeric,
character and several others.
I Matrix is a special type of array with two dimensions having data of
one type. We can find length of matrix which indicates the number of
elements in a matrix.
I Moreover, we can find dimension of a matrix using the dim() function,
something that vectors do not have.

3/4
Matrices in R

I Let us see how matrices look in R through an example. A 3 × 4 matrix


with all missing values will be expressed in R as:-
## [,1] [,2] [,3] [,4]
## [1,] NA NA NA NA
## [2,] NA NA NA NA
## [3,] NA NA NA NA

4/4
Matrices in R

I Let us see how matrices look in R through an example. A 3 × 4 matrix


with all missing values will be expressed in R as:-
## [,1] [,2] [,3] [,4]
## [1,] NA NA NA NA
## [2,] NA NA NA NA
## [3,] NA NA NA NA
I In the above matrix, we find that there are 3 rows and 4 columns;
hence the dimension of the matrix is 3 × 4.

4/4
Creating Matrices

IIT Guwahati

1/7
Creating an arbitrary Matrix
I Any arbitrary matrix can be created in R using matrix() function as:-
matrix(seq(1,20,by = 1),nrow = 2,ncol = 10, byrow = TRUE)

## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
## [1,] 1 2 3 4 5 6 7 8 9 10
## [2,] 11 12 13 14 15 16 17 18 19 20

2/7
Creating an arbitrary Matrix
I Any arbitrary matrix can be created in R using matrix() function as:-
matrix(seq(1,20,by = 1),nrow = 2,ncol = 10, byrow = TRUE)

## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
## [1,] 1 2 3 4 5 6 7 8 9 10
## [2,] 11 12 13 14 15 16 17 18 19 20
I Here the arguments nrow and ncol indicates the desired number of
rows and columns in the matrix respectively; whereas the argument
byrow is a logical argument, indicating whether or not to fill up the
matrix by row.

2/7
Creating an arbitrary Matrix
I Any arbitrary matrix can be created in R using matrix() function as:-
matrix(seq(1,20,by = 1),nrow = 2,ncol = 10, byrow = TRUE)

## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
## [1,] 1 2 3 4 5 6 7 8 9 10
## [2,] 11 12 13 14 15 16 17 18 19 20
I Here the arguments nrow and ncol indicates the desired number of
rows and columns in the matrix respectively; whereas the argument
byrow is a logical argument, indicating whether or not to fill up the
matrix by row.
I We can also create a matrix of constant value as:
## [,1] [,2] [,3]
## [1,] 99 99 99
## [2,] 99 99 99

2/7
Operations on Matrices in R

I We can calculate the dimension of the matrix mat,described in


previous slide, using the function dim() as:
d = dim(mat)
d

## [1] 2 3

3/7
Operations on Matrices in R

I We can calculate the dimension of the matrix mat,described in


previous slide, using the function dim() as:
d = dim(mat)
d

## [1] 2 3
I We can also get the number of rows and columns in a matrix using
nrow() and ncol() functions respectively. We can also find out the
total number of elements in a matrix usiong length() function as:
l = length(mat)
l

## [1] 6

3/7
More operations on Matrices in R

I We can convert a matrix into a vector using as.vector() function as:


vec = as.vector(mat)
vec

## [1] 99 99 99 99 99 99

4/7
More operations on Matrices in R

I We can convert a matrix into a vector using as.vector() function as:


vec = as.vector(mat)
vec

## [1] 99 99 99 99 99 99
I The length of the above vector will be same as the length of the matrix
and we can find it using the length() function. We can get our
original matrix from the vector as:
mat1 = matrix(data = vec,nrow = 2,ncol = 3)
mat1

## [,1] [,2] [,3]


## [1,] 99 99 99
## [2,] 99 99 99

4/7
Type of data matrix in R
I Like vectors, matrices contain data of one type. We can create
numeric, integer, character, and logical matrices by adding the
corresponding values in the data argument while creating a matrix.

5/7
Type of data matrix in R
I Like vectors, matrices contain data of one type. We can create
numeric, integer, character, and logical matrices by adding the
corresponding values in the data argument while creating a matrix.
matrix(seq(0, 4.5, length.out = 9), nrow = 3)#numeric matrix

## [,1] [,2] [,3]


## [1,] 0.0000 1.6875 3.3750
## [2,] 0.5625 2.2500 3.9375
## [3,] 1.1250 2.8125 4.5000
b = matrix(1:9, nrow = 3) #integer matrix
c = matrix(LETTERS[1:9], nrow = 3) #character matrix
d = matrix(TRUE, nrow = 3, ncol = 3) #logical matrix

I We can check the type of matrices using is.(assumed type of


matrix)() function.

5/7
Filling up elements in a matrix by row
I Suppose we create a matrix by filling up elements rowwise as:
matrix(data = 1:9, nrow = 3, byrow = TRUE)

## [,1] [,2] [,3]


## [1,] 1 2 3
## [2,] 4 5 6
## [3,] 7 8 9

6/7
Filling up elements in a matrix by row
I Suppose we create a matrix by filling up elements rowwise as:
matrix(data = 1:9, nrow = 3, byrow = TRUE)

## [,1] [,2] [,3]


## [1,] 1 2 3
## [2,] 4 5 6
## [3,] 7 8 9
I The approach of filling up elements rowwise can be understood using
the following figure:

Figure 1: Method of adding data rowwise using byrow = TRUE


6/7
Filling up elements in a matrix by column
I Suppose we create a matrix by filling up elements rowwise as:
matrix(data = 1:9, nrow = 3, byrow = FALSE)

## [,1] [,2] [,3]


## [1,] 1 4 7
## [2,] 2 5 8
## [3,] 3 6 9

7/7
Filling up elements in a matrix by column
I Suppose we create a matrix by filling up elements rowwise as:
matrix(data = 1:9, nrow = 3, byrow = FALSE)

## [,1] [,2] [,3]


## [1,] 1 4 7
## [2,] 2 5 8
## [3,] 3 6 9
I The approach of filling up elements columnwise can be understood
using the following figure:

Figure 2: Method of filling data columnwise using byrow = FALSE


7/7
Matrix functions

IIT Guwahati

1/3
Some Functions for Matrices

I Like vectors, a series of functions are present to work with matrices.


I Since matrices are based on vectors, we can use all the
functions,applicable on vectors, upon matrices. For example, we can
compute logarithmic value of all the elements in a matrix using log()
function.
I We can also check whether all the elements in a matrix are positive
using the R command all(matrix > 0).

2/3
More Functions for Matrices
I The following functions are some useful functions for matrices:

Figure 1: Some useful functions for Matrices

3/3
Mathematical Operations

IIT Guwahati

1/5
Matrices and Scalars
I Matrices are often used for arithmetic operations to solve mathematical
problems like solving system of linear equations and several others. All
mathematical operations, applied to vectors, can also be
applied to matrices.

2/5
Matrices and Scalars
I Matrices are often used for arithmetic operations to solve mathematical
problems like solving system of linear equations and several others. All
mathematical operations, applied to vectors, can also be
applied to matrices.
I One of the simplest operations is to work with a matrix and a scalar in
the following manner:
x = matrix(1:4,nrow = 2)
x+2 #adding 2 to a matrix

## [,1] [,2]
## [1,] 3 5
## [2,] 4 6
x*3 #multiplying 3 to a matrix

## [,1] [,2]
## [1,] 3 9
## [2,] 6 12
2/5
Matrices and Vectors
I We can also perform arithmetic operations using a matrix and a vector.
For example, we consider a 2 × 2 matrix and multiply it with a vector
of length 2 to get their product as:
x = matrix(1:4,nrow = 2)
y = c(5,20)
x*y

## [,1] [,2]
## [1,] 5 15
## [2,] 40 80

3/5
Matrices and Vectors
I We can also perform arithmetic operations using a matrix and a vector.
For example, we consider a 2 × 2 matrix and multiply it with a vector
of length 2 to get their product as:
x = matrix(1:4,nrow = 2)
y = c(5,20)
x*y

## [,1] [,2]
## [1,] 5 15
## [2,] 40 80
I We can compute the above product in another way as:
z = matrix(y,nrow = 2,ncol = 2)
x*z

## [,1] [,2]
## [1,] 5 15
## [2,] 40 80
3/5
Matrices and Matrices

I We can also perform arithmetic operations using two matrices,


provided that they are of the same dimension, as:
x = matrix(1:4,nrow = 2)
y = matrix(c(10,20,30,40),nrow = 2,ncol = 2)
x+y

## [,1] [,2]
## [1,] 11 33
## [2,] 22 44
x/y

## [,1] [,2]
## [1,] 0.1 0.1
## [2,] 0.1 0.1

4/5
Other Mathematical Operations on Matrices
I Other than simple arithmetic operations, R comes with a wide range of
functions for mathematical tasks that are performed on Matrices, some
of which are as follows:

5/5
Matrix Attributes

IIT Guwahati

1/7
Checking attributes of a matrix

I Similar to vectors, matrices also have some mandatory attributes like


class and can have additional attributes.

2/7
Checking attributes of a matrix

I Similar to vectors, matrices also have some mandatory attributes like


class and can have additional attributes.
I Matrices always have a specific class (c(“matrix”, “array”)), a length,
and a dimension attribute.

2/7
Checking attributes of a matrix

I Similar to vectors, matrices also have some mandatory attributes like


class and can have additional attributes.
I Matrices always have a specific class (c(“matrix”, “array”)), a length,
and a dimension attribute.
I We can check the attributes of any matrix using attributes() function
as:
x = matrix(NA,nrow = 2,ncol = 10)
attributes(x)

## $dim
## [1] 2 10

2/7
Dimension

I Any matrix has the dimension attribute which can be computed using
dim(), nrow() and ncol() functions.

3/7
Dimension

I Any matrix has the dimension attribute which can be computed using
dim(), nrow() and ncol() functions.
I For any matrix, the function dim() returns an integer vector of
length 2 where the first element represents number of rows and
second one represents number of columns in that matrix.

3/7
Dimension

I Any matrix has the dimension attribute which can be computed using
dim(), nrow() and ncol() functions.
I For any matrix, the function dim() returns an integer vector of
length 2 where the first element represents number of rows and
second one represents number of columns in that matrix.
dim(x)

## [1] 2 10
c("no. of rows" = nrow(x), "no. of columns" = ncol(x))

## no. of rows no. of columns


## 2 10

3/7
Length and Type of Matrix
I The length of a matrix is simply the total number of elements of the
matrix, or the length of the underlying atomic vector.It can be found
using length() function.

4/7
Length and Type of Matrix
I The length of a matrix is simply the total number of elements of the
matrix, or the length of the underlying atomic vector.It can be found
using length() function.
I Similar to vectors, type of data in a matrix can be determined by
functions class() and typeof() which tells us the type of the data
present in the matrix or whether the matrix is of class matrix or array.

4/7
Length and Type of Matrix
I The length of a matrix is simply the total number of elements of the
matrix, or the length of the underlying atomic vector.It can be found
using length() function.
I Similar to vectors, type of data in a matrix can be determined by
functions class() and typeof() which tells us the type of the data
present in the matrix or whether the matrix is of class matrix or array.
x <- matrix(c(1L, 2L, 3L, 4L), ncol = 2)
length(x)

## [1] 4
class(x)

## [1] "matrix" "array"


typeof(x)

## [1] "integer"

4/7
Dimension Names
I The function names(), which works for vectors, no longer works for
matrices as they are two-dimensional.

5/7
Dimension Names
I The function names(), which works for vectors, no longer works for
matrices as they are two-dimensional.
I For matrices, we have rownames() indicating names of rows in a
matrix, colnames() indicating names of columns in a matrix and
dimnames() indicating all the dimension names.
x <- matrix(data = 1:9, nrow = 3, ncol = 3)
rownames(x)

## NULL

5/7
Dimension Names
I The function names(), which works for vectors, no longer works for
matrices as they are two-dimensional.
I For matrices, we have rownames() indicating names of rows in a
matrix, colnames() indicating names of columns in a matrix and
dimnames() indicating all the dimension names.
x <- matrix(data = 1:9, nrow = 3, ncol = 3)
rownames(x)

## NULL
rownames(x) <- c("Row 1", "Row 2", "Row 3")
colnames(x) <- c("Col A", "Col B", "Col C")
x

## Col A Col B Col C


## Row 1 1 4 7
## Row 2 2 5 8
## Row 3 3 6 9
5/7
Changing Dimension Names
I At any point of time, we can use rownames() and colnames() to
change the existing names in a matrix as:
colnames(x) <- c("first","second","third")
x

## first second third


## Row 1 1 4 7
## Row 2 2 5 8
## Row 3 3 6 9

6/7
Changing Dimension Names
I At any point of time, we can use rownames() and colnames() to
change the existing names in a matrix as:
colnames(x) <- c("first","second","third")
x

## first second third


## Row 1 1 4 7
## Row 2 2 5 8
## Row 3 3 6 9
I We can also change the name of a specific column in a matrix:
colnames(x)[2] <- "Coursera"
x

## first Coursera third


## Row 1 1 4 7
## Row 2 2 5 8
## Row 3 3 6 9
6/7
Creating Named Matrices
I We can directly create named matrices using the matrix() function as:
x <- matrix(data = 1:9, nrow = 3, ncol = 3,
dimnames = list(c("Row_1", "Row_2", "Row_3"),
c("Col_A", "Col_B", "Col_C")))
x

## Col_A Col_B Col_C


## Row_1 1 4 7
## Row_2 2 5 8
## Row_3 3 6 9

7/7
Creating Named Matrices
I We can directly create named matrices using the matrix() function as:
x <- matrix(data = 1:9, nrow = 3, ncol = 3,
dimnames = list(c("Row_1", "Row_2", "Row_3"),
c("Col_A", "Col_B", "Col_C")))
x

## Col_A Col_B Col_C


## Row_1 1 4 7
## Row_2 2 5 8
## Row_3 3 6 9
I We can set either of the rownames or colnames to their original version
as:
x1 <- matrix(data = 1:9, nrow = 3, ncol = 3,
dimnames = list(NULL,
c("Col A", "Col B", "Col C")))

7/7
Combine Objects

IIT Guwahati

1/5
Multiple Vectors
I A possible way of creating matrices in R is by combining two or more
vectors rowwise or columnwise as:
x <- c( 5, 5, 5)
y <- c(11, 22, 33)
z <- cbind(x,y) #combining columnwise
z

## x y
## [1,] 5 11
## [2,] 5 22
## [3,] 5 33

2/5
Multiple Vectors
I A possible way of creating matrices in R is by combining two or more
vectors rowwise or columnwise as:
x <- c( 5, 5, 5)
y <- c(11, 22, 33)
z <- cbind(x,y) #combining columnwise
z

## x y
## [1,] 5 11
## [2,] 5 22
## [3,] 5 33
u = rbind(x,y) #combining columnwise
u

## [,1] [,2] [,3]


## x 5 5 5
## y 11 22 33
2/5
Dimension Names While Combining Vectors
I R automatically assigns dimension names while using cbind() or
rbind() as:
par_age <- c(24, 25, 21)
par_height <- c(1.73, 1.62, 1.72)
par = rbind(age = par_age,height = par_height)
par

## [,1] [,2] [,3]


## age 24.00 25.00 21.00
## height 1.73 1.62 1.72

3/5
Dimension Names While Combining Vectors
I R automatically assigns dimension names while using cbind() or
rbind() as:
par_age <- c(24, 25, 21)
par_height <- c(1.73, 1.62, 1.72)
par = rbind(age = par_age,height = par_height)
par

## [,1] [,2] [,3]


## age 24.00 25.00 21.00
## height 1.73 1.62 1.72
par_1 = cbind(age = par_age,height = par_height)
par_1

## age height
## [1,] 24 1.73
## [2,] 25 1.62
## [3,] 21 1.72
3/5
Multiple Matrices
I We can also create a matrix in R by combining two matrices rowwise or
columnwise as:
x1 <- matrix(1:2,ncol = 1,
dimnames =list(c("R_1", "R_2"),c("A")))
x2 <- matrix(101:102, ncol = 1,
dimnames = list(c("R_1", "R_2"),c("A")))
cbind(x1,x2) #combining columnwise

## A A
## R_1 1 101
## R_2 2 102

4/5
Multiple Matrices
I We can also create a matrix in R by combining two matrices rowwise or
columnwise as:
x1 <- matrix(1:2,ncol = 1,
dimnames =list(c("R_1", "R_2"),c("A")))
x2 <- matrix(101:102, ncol = 1,
dimnames = list(c("R_1", "R_2"),c("A")))
cbind(x1,x2) #combining columnwise

## A A
## R_1 1 101
## R_2 2 102
rbind(x1,x2) #combining rowwise

## A
## R_1 1
## R_2 2
## R_1 101
## R_2 102
4/5
Matrices and Vectors
I We can also create a matrix in R by combining vectors and matrices as:
x <- matrix(1:6, nrow = 3)
y <- c(900, 800,600)
cbind(x,y)

## y
## [1,] 1 4 900
## [2,] 2 5 800
## [3,] 3 6 600

5/5
Matrices and Vectors
I We can also create a matrix in R by combining vectors and matrices as:
x <- matrix(1:6, nrow = 3)
y <- c(900, 800,600)
cbind(x,y)

## y
## [1,] 1 4 900
## [2,] 2 5 800
## [3,] 3 6 600
options(width = 30)
w = rbind(x,y) # It will provide an error.

## Warning in rbind(x, y):


## number of columns of result
## is not a multiple of vector
## length (arg 2)

5/5
Subsetting Matrices

IIT Guwahati

1 / 14
Schematic Representation of a Matrix
I The schematic representation of a matrix can be seen in the figure
below:

2 / 14
Schematic Representation of a Matrix
I The schematic representation of a matrix can be seen in the figure
below:

I The above matrix can be created in R using the sprintf() command:


x = matrix(sprintf("x[%d, %d]",rep(1:3, 4),
rep(1:4, each = 3)),nrow = 3)
x

## [,1] [,2] [,3] [,4]


## [1,] "x[1, 1]" "x[1, 2]" "x[1, 3]" "x[1, 4]"
## [2,] "x[2, 1]" "x[2, 2]" "x[2, 3]" "x[2, 4]"
## [3,] "x[3, 1]" "x[3, 2]" "x[3, 3]" "x[3, 4]"

2 / 14
Subsetting by index through the extraction of single element
I For matrices, we can access elements in a specific row and column in a
way similar to vectors, except that we have to specify the rows and the
columns as:
x[3,1]

## [1] "x[3, 1]"


x[3] #Subsetting by index of first element

## [1] "x[3, 1]"

3 / 14
Subsetting by index through the extraction of single element
I For matrices, we can access elements in a specific row and column in a
way similar to vectors, except that we have to specify the rows and the
columns as:
x[3,1]

## [1] "x[3, 1]"


x[3] #Subsetting by index of first element

## [1] "x[3, 1]"


I Thus, the matrix representation in the previous slide after subsetting by
index turns out to be:

Figure 1: Matrix Representation after subsetting index

3 / 14
Subsetting by index through extraction of multiple elements
I Like vectors, we can extract multiple elements from any matrix at the
same time.We can extract multiple rows for a specific column and vice
versa as:
mat = matrix(101:112,nrow = 4,ncol = 3)
mat[c(4,2),2] #Vector subsetting

## [1] 108 106


mat[1,1:3] #Matrix subsetting

## [1] 101 105 109

4 / 14
Subsetting by index through extraction of multiple elements
I Like vectors, we can extract multiple elements from any matrix at the
same time.We can extract multiple rows for a specific column and vice
versa as:
mat = matrix(101:112,nrow = 4,ncol = 3)
mat[c(4,2),2] #Vector subsetting

## [1] 108 106


mat[1,1:3] #Matrix subsetting

## [1] 101 105 109


I Matrix subsetting does not work for extraction of pairs of rows and
columns:
mat[c(2,3),c(1,2)]

## [,1] [,2]
## [1,] 102 106
## [2,] 103 107
4 / 14
Subsetting by index through extraction of rows or columns
I We can extract an entire row or column rather than extracting a single
element:
mat[1,] #Returns entire 1st row

## [1] 101 105 109


mat[,3] #Returns entire 3rd column

## [1] 109 110 111 112

5 / 14
Subsetting by index through extraction of rows or columns
I We can extract an entire row or column rather than extracting a single
element:
mat[1,] #Returns entire 1st row

## [1] 101 105 109


mat[,3] #Returns entire 3rd column

## [1] 109 110 111 112


I We can also partially extract elements from a row or column by
specifying the index vector as:
mat[1,c(2,3),drop = FALSE]

## [,1] [,2]
## [1,] 105 109

5 / 14
Subsetting by name through the extraction of single element

I we can access elements using corresponding row names and column


names from any matrix:
oly <- c("USA", "England", "Canada", "USSR", "Swiss")
medals <- matrix(c(3,3,2,1,1,4,1,1,0,0,1,5,1,2,2),
ncol = 3,
dimnames = list(oly,c("G", "S", "B")))
medals[3,1]

## [1] 2
medals["Canada", "G"] #Subsetting by name

## [1] 2

6 / 14
Subsetting by name through extraction of rows or columns
I We can extract an entire row or column by names but the output will
be a named vector. The output will be a matrix only when we specify
drop = FALSE while extracting rows or columns as:
medals["Canada", ] #Output is a named vector

## G S B
## 2 1 1
medals["Canada", , drop = FALSE] #Output is a matrix

## G S B
## Canada 2 1 1

7 / 14
Subsetting by name through extraction of rows or columns
I We can extract an entire row or column by names but the output will
be a named vector. The output will be a matrix only when we specify
drop = FALSE while extracting rows or columns as:
medals["Canada", ] #Output is a named vector

## G S B
## 2 1 1
medals["Canada", , drop = FALSE] #Output is a matrix

## G S B
## Canada 2 1 1
I We can use further processing of above matrix to extract second
element:
medals["Canada", , drop = FALSE][2]

## [1] 1
7 / 14
Subsetting by logical vectors
I We can use logical vectors for subsetting a matrix in the following
manner:
id = medals[, "G"] > 2 #Logical vector
medals[id,] # Subsetting matrix by logical vector

## G S B
## USA 3 4 1
## England 3 1 5

8 / 14
Subsetting by logical vectors
I We can use logical vectors for subsetting a matrix in the following
manner:
id = medals[, "G"] > 2 #Logical vector
medals[id,] # Subsetting matrix by logical vector

## G S B
## USA 3 4 1
## England 3 1 5
I We can perform subsetting by logical vectors working in combination
with vector subsetting as:
which(medals>3,arr.ind = TRUE)

## row col
## USA 1 2
## England 2 3

8 / 14
Replacing elements in a matrix
I A nice practical application for subsetting with logical vectors is search
and replace where we can search all the elements that are needed to
be replaced and then replace them as:
x <- round(matrix(runif(10), nrow = 5,ncol = 2),1)
x[x>0.5] #Searching elements greater than 0.5

## [1] 0.7 0.9 1.0 0.7

9 / 14
Replacing elements in a matrix
I A nice practical application for subsetting with logical vectors is search
and replace where we can search all the elements that are needed to
be replaced and then replace them as:
x <- round(matrix(runif(10), nrow = 5,ncol = 2),1)
x[x>0.5] #Searching elements greater than 0.5

## [1] 0.7 0.9 1.0 0.7


x[x>0.5] = 0.5 #Replacing all the searched elements by 0.5
x

## [,1] [,2]
## [1,] 0.5 0.5
## [2,] 0.5 0.5
## [3,] 0.5 0.5
## [4,] 0.0 0.3
## [5,] 0.5 0.3

9 / 14
Mixed Subsetting

I Subsetting methods can always be mixed which could be important if


we have a matrix that has row names, but no column names, or vice
versa.

10 / 14
Mixed Subsetting

I Subsetting methods can always be mixed which could be important if


we have a matrix that has row names, but no column names, or vice
versa.
medals[3, "G"] #Subsetting both by index and name

## [1] 2

10 / 14
Mixed Subsetting

I Subsetting methods can always be mixed which could be important if


we have a matrix that has row names, but no column names, or vice
versa.
medals[3, "G"] #Subsetting both by index and name

## [1] 2
id <- medals[, "G"] > 1
medals[id,"S"] #Subsetting by logical vector

## USA England Canada


## 4 1 1

10 / 14
Out of range Indexes

I In the case of vectors, we already know that NA will be returned if we


access an element that does not exist. But, for matrices, we will get an
error if we try to access elements that are not defined.

11 / 14
Out of range Indexes

I In the case of vectors, we already know that NA will be returned if we


access an element that does not exist. But, for matrices, we will get an
error if we try to access elements that are not defined.
x <- matrix(1:6, nrow = 3)
a = x[5,5] #Out of range indexes

## Error in x[5, 5]: subscript out of bounds

11 / 14
Out of range Indexes

I In the case of vectors, we already know that NA will be returned if we


access an element that does not exist. But, for matrices, we will get an
error if we try to access elements that are not defined.
x <- matrix(1:6, nrow = 3)
a = x[5,5] #Out of range indexes

## Error in x[5, 5]: subscript out of bounds


x <- matrix(1:9,nrow = 3,
dimnames = list(LETTERS[1:3],letters[1:3]))
b = x["B", "f"] #Out of range;hence error

## Error in x["B", "f"]: subscript out of bounds

11 / 14
Summary of Subsetting Matrices

I A quick summary regarding methods of subsetting matrices can be


seen in the following figure:

Figure 2: Summary of Methods for Subsetting Matrices

12 / 14
Sorting a Matrix
I Similar to vectors, we can perform sorting on a matrix using the
command sort().But we can only sort a specific column or row of the
matrix using sort() in the following manner:
stud <- matrix(c(24, 30, 24, 1.67, 1.93, 1.71, 5, 3, 2),
nrow = 3,dimnames = list(c("B","E","C"),
c("age","height","year")))
sort(stud[,"age"]) #increasing order sorting

## B C E
## 24 24 30

13 / 14
Sorting a Matrix
I Similar to vectors, we can perform sorting on a matrix using the
command sort().But we can only sort a specific column or row of the
matrix using sort() in the following manner:
stud <- matrix(c(24, 30, 24, 1.67, 1.93, 1.71, 5, 3, 2),
nrow = 3,dimnames = list(c("B","E","C"),
c("age","height","year")))
sort(stud[,"age"]) #increasing order sorting

## B C E
## 24 24 30
#decreasing order sorting
sort(stud[,"year"],decreasing = TRUE)

## B E C
## 5 3 2

13 / 14
Re-Ordering a Matrix

I For re-ordering any matrix, we use the function order() which returns
the position of the elements in the matrix from smallest to largest or
vice versa.

14 / 14
Re-Ordering a Matrix

I For re-ordering any matrix, we use the function order() which returns
the position of the elements in the matrix from smallest to largest or
vice versa.
correct_order <- order(stud[,"year"]) #Re-Ordering
correct_order

## [1] 3 2 1

14 / 14
Re-Ordering a Matrix

I For re-ordering any matrix, we use the function order() which returns
the position of the elements in the matrix from smallest to largest or
vice versa.
correct_order <- order(stud[,"year"]) #Re-Ordering
correct_order

## [1] 3 2 1
stud[correct_order,] # Re-ordered matrix

## age height year


## C 24 1.71 2
## E 30 1.93 3
## B 24 1.67 5

14 / 14
Plotting Matrices

IIT Guwahati

1/9
Plotting Functions For Matrices

I There are several functions for plotting matrices, some of which are
given below:

2/9
Plotting Functions For Matrices

I There are several functions for plotting matrices, some of which are
given below:

Figure 1: Plotting Functions for Matrices

2/9
Generic X-Y plot of Matrix
I Using plot() function, R can plot any two columns of a matrix (if not
stated then first two) against each other ;thereby creating a 2d
scatter plot as:

3/9
Generic X-Y plot of Matrix
I Using plot() function, R can plot any two columns of a matrix (if not
stated then first two) against each other ;thereby creating a 2d
scatter plot as:
x <- seq(0, 2 * pi, length.out = 200)
m <- cbind("sft: 0" = sin(x),"sft: pi" = sin(x + pi))
plot(m,main = "Generic X-Y Plot")
Generic X−Y Plot
1.0
0.5
sft: pi

0.0
−0.5
−1.0

−1.0 −0.5 0.0 0.5 1.0

sft: 0

3/9
Matrix Plot
I Using matplot() function, R can plot data matrix columnwise where
each column gets a different colour and line type(or symbol if type =
“p” as default) as:

4/9
Matrix Plot
I Using matplot() function, R can plot data matrix columnwise where
each column gets a different colour and line type(or symbol if type =
“p” as default) as:
matplot(m,type = "l",main = "Matrix Plot")
Matrix Plot
1.0
0.5
0.0
m

−0.5
−1.0

0 50 100 150 200

4/9
Customized Matrix Plot
I We can customize our matrix plot as:

5/9
Customized Matrix Plot
I We can customize our matrix plot as:
matplot(x, m,type = "l",xlab = NA,
main = "Customized Matrix Plot")
legend("topleft",legend = colnames(m),col = 1:2,lty = 1:2)
axis(side = 1,at = c(0, pi, 2 * pi),line = 1,lwd = 0,
c(expression(0), expression(pi), expression(2 * pi)),
col = "steelblue") #Adding custom second axis
Customized Matrix Plot
1.0

sft: 0
sft: pi
0.5
0.0
m

−0.5
−1.0

0 1 2 3 4 5 6
0 π 2π 5/9
Image Plot
I For two dimensional data, we can plot them using image()
function.Let us consider a R dataset volcano to get an image plot as:

6/9
Image Plot
I For two dimensional data, we can plot them using image()
function.Let us consider a R dataset volcano to get an image plot as:
data("volcano")
class(volcano)

## [1] "matrix" "array"


dim(volcano)

## [1] 87 61
image(volcano,main = "Image Plot")
Image Plot
1.0
0.8
0.6
0.4
0.2
0.0

0.0 0.2 0.4 0.6 0.8 1.0

6/9
Customized Image Plot
I We can also customize our image plot by changing the value of axes
and labelling them as:

7/9
Customized Image Plot
I We can also customize our image plot by changing the value of axes
and labelling them as:
image(x = 1:nrow(volcano),
y = 1:ncol(volcano),
z = volcano,
col = hcl.colors(100, "terrain"))
60
50
40
1:ncol(volcano)

30
20
10

20 40 60 80

1:nrow(volcano)

7/9
Contour Plot
I We can plot a series of contours in R using contour() function,which
works similar to image plot, as:

8/9
Contour Plot
I We can plot a series of contours in R using contour() function,which
works similar to image plot, as:
contour(volcano,main = "Contour Plot")
Contour Plot
1.0

110

110 120

100
0.8

170

160
0.6

130
150 150

180
170
0.4

190

180 160

140
0.2

10
0
110

100
110
0.0

0.0 0.2 0.4 0.6 0.8 1.0

8/9
Filled Contour Plot
I The filled contour plot does the same as contour plot but fills the area
between two contours instead of drawing them as lines in the following
manner:

9/9
Filled Contour Plot
I The filled contour plot does the same as contour plot but fills the area
between two contours instead of drawing them as lines in the following
manner:
filled.contour(volcano,main = "Filled Contour Plot")
Filled Contour Plot

1.0

180
0.8

160

0.6

140

0.4

120

0.2

100

0.0
0.0 0.2 0.4 0.6 0.8 1.0

9/9

You might also like