Matrices – Two Dimensional Masters of R

Welcome to the third edition in a series of follow along tutorials in R Programming. Today we will be discussing Matrices: You can use the code below to practice and learn – A thorough exercise here can ensure you that you do not fail interviews related to R Programming

# A matrix is a vector with two additional attributes, the number of
# rows and number of columns

# Basically if we call the ‘attributes’ function over a vector than it
# be null, the same applied on a matrix, results in two attributes

x = c(1,2,3,4)
attributes(x)
dim(x)

# We can create matrix using an existing vector and ‘matrix()’ function

y = matrix(x, nrow = 2, ncol = 2)
attributes(y)
dim(y)

# As one can see from above We can also create a matrix using ‘dim()’function
x = c(1,2,3,4)
dim(x) = c(2,2)
attributes(x)
is.matrix(x)

# Creating a blank 2*2 matrix
y = matrix(nrow = 2,ncol = 2)

# Default behaviour of matrix() function
x = c(1:6)
x = matrix(x)
x

# Internally R stores a matrix in a column major order…which means
# first column 1 is populated, then column 2 and so on…for row major order
m = matrix(x, 2, 2, byrow = TRUE)
m

# Create a transpose of matrix
t(m)

# ———————-Creating two matrix using rbind and cbind—————————-

x = c(1:4)
y = c(2:5)
z = c(3:6)

cbind(x,y,z)
# Also try – cbind(C(x,y,z))

rbind(x,y,z)

#—————————— Questions on rbind and cbind——————————–

x = c(2,5,6,74,1)
y = c(‘a’,’b’,’c’,’d’,’e’)
# cbind(x,y)

x = c(1,2)
y = c(1,2,3,4)
z = c(1:6)

# cbind(x,y)

# cbind(y,z)

cbind(x,z)

x = c(2,3,5,6,7)
y = c(2,9,4,8,7,6)
z = c(1,2,3,4)

cbind(x,y,z)

# Create a 5th column using cbind, flood it with any value
x = c(22,11,5,4,32,3,4,22,89,34,22,12,45,09,NA,22)

m = matrix(x,4,4)
m
#———————————————————————-
# Joining two matrix using cbind and rbind

# Using Recycling
newMatrix = cbind(m,1)

# Combining two matrices
newMatrix = cbind(m,x)
newMatrix

# Using Recycling
newMatrix = rbind(m,1)
newMatrix

# Combining two matrices
newMatrix = rbind(m,x)
newMatrix

# ————–Questions on joining matrices using cbind and rbind—————————
x = matrix(data = c(22,3,4,12,3,4,56,23,21,56,44,65), ncol = 4)
y = matrix(data = c(76,12,34,44,2,5,2,6,11,55,1,67,77,34,11), ncol = 5)
cbind(x,y)
rbind(x,y)
x = matrix(data = c(1:4), ncol = 2)
y = matrix(data = c(1:6), ncol = 2)

# is joining the two matrix using cbind possible
x = matrix(1:26, ncol = 2)
y = matrix(2:40, ncol = 3)

# Perform all the above excercise using rbind

# —————————————————————-

# What happens if we specify a dimension from which matrix cannot be created
x = c(1,2,3,4)

matrix(x, 2,3)

x = c(1,2,3,4,5)
# By default if we do not specify nrow and ncol then nrow = 1, ncol = 1
# hence if there are more than one elements, it forms that many rows
# Thumb rule is number of rows that we specify should be multiple or
# submultiple of number of rows
matrix(x)
matrix(x,10,4)

x = matrix(c(1:6), nrow = 3, ncol = 2)
x
# Concept of Recycling at play
matrix(x, 4,2)
matrix(x, 8, 4)

# ————————————————————-

# By default the names of rows is referred to as [1,]…, and columns
# by [,1],[,2]…..we can change this to any name

dim(x) = c(2,2)
rownames(x) = paste(‘row’, 1:2)
x
colnames(x) = paste(‘col’, 1:2)
x

# To specify specific names
rownames(x) = c(‘a’, ‘b’)
x
colnames(x) = c(‘p’, ‘q’)
x

#——————————————————————-
# Indexing Matrix

x = c(22,11,5,4,32,3,4,22,89,34,22,12,45,09,NA,22)

m = matrix(x,4,4)
# To output the first row
m[1,]

# To output the first and second row
m[1:2,]

# To output the first and the third row
m[c(1,3),]

# To output all but first and third row
m[-c(1,3),]

# To output a sub matrix where first column should be col – 3 and second column should be col – 1
m[,c(3,1)]

# To output all rows if we do not know the number of rows
m[1:nrow(m),]

# To output the first column
m[,1]

# To output the second and 3rd column
m[,2:3]

# To output 1st and 3rd column
m[,c(1,3)]

# To output every column except 1st and 3rd
m[,-c(1,3)]

# To output column 4 first followed by column 1
m[, c(4,1)]

# To output all columns
m[,1:ncol(m)]
# ————————————————————-

# Excercises
# 1. Create 4 vectors and 4*4 matrix and name their rows and columns
# naming to be done using row1, row2…

# 2. Create a 5*4 matrix and name them uniquely

# 3. Using the matrix created in question 1, create a sub matrix
# which contains only the values of last two rows

# 4. Create a 3*4 matrix ‘m’ and then obtain its transpose ‘Tm’

# 5. Is it possible to do a conventional matrix multiplication on the
# above created matrices ‘m’ and ‘Tm’

# —————————————————————-

# Matrix Arithmetic

m
m+1
m + matrix(data = c(2,4,5,6), nrow = 2,2)

# Non conformable array
m + matrix(data = c(1:16), 4, 4)

# Why??
m + matrix(data = c(1,2,3,4))

# Conventional matrix arithmetic in R

m = matrix(c(1,2,3,4), 2,2)
n = matrix(c(2,3,4,5), 2, 2)
m*n
m%*%n

# —————————————————————
# Subsetting Matrices

x = c(22,11,5,4,32,3,4,22,89,34,22,12,45,09,NA,22)

m = matrix(x,4,4)

m

# Extracting the first element of matrix
m[1,1]

# We can also extract the first element of matrix using
m[1]

# Extract the element present 4th row and 3rd column
m[4,3]

# Can we do the above thing in the below way:
m[12]

# Check if any value in colmn 2 is greater than 40
any(m[,2] > 40)

# Check if all value in row2 is greater than 5
all(m[2,] > 5)

# Check what is the smallest value in row 2 of the matrix
which.min(p[2,])
p[2,4]

min(p[2,])

x = c(22,11,5,4,32,3,4,22,89,34,22,12,45,09,NA,22)
length(x)
# Create a 4*4 matrix
m = matrix(x,4,4)
m

# Find the position of 22 in matrix m and interpret it

which(m == 22)

# Check for NA
is.na(m)
sum(is.na(m))
m

# Replace the value of NA by 12
m[is.na(m)] = 0
m

# Exchange the values of 1st and 3rd column
m[,1] = m[,3]
m

m[,c(1,3)] = m[,c(3,1)]
m
# ————————————-functions on matrices————————————

x = c(22,11,5,4,32,3,4,22,89,34,22,12,45,09,NA,22)
# Create a 4*4 matrix
m = matrix(x,4,4)

# To obtain the sum of each row
apply(m,1,sum)

# To obtain the sum of each column
apply(m,2,sum)

# To find mean of each row
apply(m,1,mean)

# To find square root of each column
apply(m,2,sqrt)

# To find the minimum and maximum in each column
apply(m,2, max)

# ————————-sorting matrix———————————————-
x = c(22,11,5,4,32,3,4,22,89,34,22,12,45,09,NA,22)
# Create a 4*4 matrix
m = matrix(x,4,4)

m
# sort 1st column
# sort(m[,1])

m[,1] = sort(m[,1])
m

# Sort this in decreasing order

# Sort 4th column since it has NA
m[,4] = sort(m[,4])

# Replace NA with 34
m[is.na(m)] = 34
m

# Now easily sort the 4th column

# Sort by 3rd row
m[2,] = sort(m[2,])

# Sort the entire matrix by 3rd row and 2nd col
m1row = m[,order(m[3,])]
m1row
m

m2col = m[order(m[,2]),]
m2col
m

# To order it in reverse
m1row = m[,order(-m[3,])]
m1row
m

m2col = m[order(-m[,2]),]
m2col

Leave a Reply

Your email address will not be published. Required fields are marked *