R Programming matrix exercises-part2
Get element at the specific position from matrix in R
At any point in
time, a matrix may be required to be traversed for an element at a specific
position. we are going to access the elements from a matrix in
R Programming Language using integer vector, logical vector as the index.
Method 1: Accessing
elements using integer vector
Integer vector is a vector, that
includes all elements of integer type.
Syntax:
matrix_name[row_vector_with_values,column_vector_with_values,]
Example:
select rows 1 & 3 and
columns 1 & 3 of matrix a.
print(a )
Program:
# create a vector named data with 9 elements
data=c(1,2,3,4,5,6,7,8,9)
# pass this vector to matrix input
a=matrix(data, nrow = 3, ncol = 3)
print(a)
# select rows 1 & 3 and columns 1 & 3
print(a[c(1,3),c(1,3)] )
# select rows 1 & 2 and columns 1 & 2
print(a[c(1,2),c(1,2)] )
# select rows 2 & 1 and columns 2 & 2
print(a[c(2,1),c(2,2)] )
Method 2: Accessing
matrix elements using logic vector
Logical vector includes a vector
comprising boolean values i.e. TRUE or FALSE.
Syntax :
matrix_name[logical_vector]
If TRUE at that position, matrix
element is accessed
If FALSE at that position, matrix
element is not accessed.
Example:
data=c(TRUE,TRUE,FALSE)
Program
1:
# create a vector named data with 9 elements
data=c(1,2,3,4,5,6,7,8,9)
# pass this vector to matrix input
a=matrix(data, nrow = 3, ncol = 3)
print(a)
a[c(TRUE, FALSE,TRUE, FALSE,TRUE, FALSE,TRUE, FALSE,TRUE)]
# accessing elements
Program 2:
# create a vector named data with 9 elements
data=c(1,2,3,4,5,6,7,8,9)
# pass this vector to matrix input
a=matrix(data, nrow = 3, ncol = 3)
print(a)
print(a[c(TRUE)])
# accessing elements by placing all TRUE
print(a[c(FALSE)])
# accessing elements by placing all FALSE
Find row and column index of maximum and minimum value in a matrix in R
Finding Maximum value:
·
In the code below, we
have created a sample matrix, in which we have passed “nrow=3“(matrix
will have only 3 rows) in example 1 and “ncol=2“(matrix will have only 2 columns) in
example 2.
·
Then we have printed the
sample matrix in the next line with the message “Sample Matrix”.
·
Then we have used the
syntax below to find the row and column number of the maximum element and
stored it in the variable “max”. We have made use of the max() function which is used to find the
maximum element present in an object. This object can be a
Vector, a list, a matrix, a data frame, etc.
·
The “which()” function is used to get the index or position of the
value which satisfies the given condition. Then we have printed
the maximum value along with its row and column index.
Syntax: which(m == max(m), arr.ind=TRUE)
Example 1:
# defining a sample matrix
m = matrix(c(11, 20, 13, -9, 1, 99, 36, 81, 77),
nrow
= 3)
print("Sample Matrix:")
print(m)
# stores indexes of max value
max = which(m == max(m), arr.ind = TRUE)
print(paste("Maximum value: ", m[max]))
print(max)
Example 2:
# defining a sample matrix
m = matrix(c(1:16), ncol = 2)
print("Sample Matrix:")
print(m)
# stores indexes of max value
max = which(m == max(m), arr.ind=TRUE)
print(paste("Maximum value: ",m[max]))
print(max)
Finding Minimum value:
·
In the code below, we
have created a sample matrix, in which we have passed “nrow=3“(matrix
will have only 3 rows) in example 1 and “ncol=8“(matrix will have only 8 columns) in
example 2 as a parameter while defining the matrix.
·
Then we have printed the
sample matrix in the next line with the message “Sample Matrix”.
·
Then we have used the
syntax below to find the row and column number of the minimum element and
stored it in the variable “min”. We have made use of the min() function which is used to find the
minimum element present in an object. This object can be a
Vector, a list, a matrix, a data frame, etc.
·
The
“which()” function is used to get the index or position of the value which
satisfies the given condition. Then we have printed the minimum value along with its row
and column index.
Syntax: which(m == min(m), arr.ind=TRUE)
Example 1:
# defining a sample matrix
m = matrix(c(11, 20, 13, -9, 1, 99, 36, 81, 77), nrow =
3)
print("Sample Matrix:")
print(m)
# stores indexes of min value
min = which(m == min(m), arr.ind = TRUE)
print(paste("Minimum value: ", m[min]))
print(min)
Example 2:
# defining a sample matrix
m = matrix(c(1:16), ncol = 8)
print("Sample Matrix:")
print(m)
# stores indexes of min value
min = which(m == min(m), arr.ind = TRUE)
print(paste("Minimum value: ", m[min]))
print(min)
Select rows of a matrix in R that meet a condition
A large dataset is
often required to be filtered according to our requirements. we will be
discussing how we can select a row from a matrix in R that meets the condition.
For better understanding let’s understand the problem statement with the help
of an example.
Example:
Now, as the problem statement is that we
want to select the rows of the matrix that meets the given condition. Suppose
we want to select the rows from the matrix whose car_color = Red.
pproach:
·
Create dataset
·
Specify the condition
·
Pass it to the matrix
·
Select rows which specify this condition
Syntax:
dataset[condition]
Example:
mat[mat[,”car_color”]==”Red”,]
Here, Comma(‘,’) is used
to return all the matrix rows.
·
Copy the resultant dataset to auxiliary dataset
·
Display dataset
#
Creating Dataset
car_models
<- c('Maruti','Hyundai','Tata',
'Ford','Nissan','Toyota')
car_type
<- c('Diesel','Petrol','Petrol',
'Diesel','Petrol','Diesel')
car_color
<- c('Red','Blue','Red',
'Red','Blue','Red')
year
<- c(2001,2011,2013,2012,2021,2021)
#
Storing matrix in mat (variable)
mat
<- cbind(car_models,car_type,car_color,year)
#
condition to select only rows with
# color
= Red
mat
<- mat[mat[,"car_color"]=="Red",]
#
displaying the resultant matrix
mat
How to multiply a matrix by its transpose while ignoring missing values
in R ?
The replacement of
values, can be performed in O(n*m), where n is the number of rows and m is the
number of columns. Replacing by 0s doesn’t affect the multiplicative product,
and therefore, this is an effective solution. The transpose can then be
calculated by using t(matrix). The product can be calculated by the following
syntax in R :
m1 %*% m2 , where m1 and m2 are the matrices involved.
If m1 is the matrix of n*m dimensions
and m2 of m*n (since it’s the transpose), the product matrix obtained is a
square matrix is n * n .
Example 1:
# declaring matrix
mat = matrix(c(1, NA, 2, 3, NA, 4), ncol = 2)
# replacing matrix NA with 0s
mat[is.na(mat)] = 0
# printing original matrix
print ("Original Matrix")
print (mat)
# calculating transpose of the
# matrix
transmat = t(mat)
print ("Transpose Matrix")
print (transmat)
# calculating product of matrices
prod = mat%*%transmat
print ("Product Matrix")
print (prod)
The original
matrix is of the dimensions 3 x 2 and the transpose is of the dimension 2×3. On
replacing the missing values with 0 and multiplying these two together, we
obtain the product matrix equivalent to 3×3 square matrix.
Example 2: The original
matrix is of the dimensions 1 x 3 and the transpose is of the dimension 3×1. On
replacing the missing values with 0 and multiplying these two together, we
obtain the product matrix equivalent to 1×1 square matrix, which is basically a
singular cell matrix.
# declaring matrix
mat = matrix(c(10, NA, 7), ncol = 3)
# replacing matrix NA with 0s
mat[is.na(mat)] = 0
# printing original matrix
print ("Original Matrix")
print (mat)
# calculating transpose of the
# matrix
transmat = t(mat)
print ("Transpose Matrix")
print (transmat)
# calculating product of matrices
prod = mat%*%transmat
print ("Product Matrix")
print (prod)
Comments
Post a Comment