UNIT 2 MATRICES, ARRAYS AND LISTS
Matrices, Arrays and Lists - Creating matrices Matrix operations Applying Functions to
Matrix Rows and Columns Adding and deleting rows and columns Vector/Matrix Distinction
Avoiding Dimension Reduction Higher Dimensional arrays lists Creating lists General list
operations Accessing list components and values applying functions to lists recursive lists.
R-Matrices
R-matrix is a two-dimensional arrangement of data in rows and columns. In a matrix, rows
are the ones that run horizontally and columns are the ones that run vertically. In R
programming, matrices are two-dimensional, homogeneous data structures. These are some
examples of matrices:
Creating a Matrix in R
To create a matrix in R you need to use the function called matrix().The arguments to
this matrix() are the set of elements in the vector. You have to pass how many numbers of
rows and how many numbers of columns you want to have in your matrix.
Syntax
matrix(data, nrow, ncol, byrow, dimnames)
Parameters:
data : values you want to enter
nrow : no. of rows
ncol : no. of columns
byrow : logical clue, if 'true' value will be assigned by rows
dimnames : names of rows and columns
Example:
A = matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
rownames(A) = c("a", "b", "c")
colnames(A) = c("c", "d", "e")
cat("The 3x3 matrix:\n")
print(A)
Output
The 3x3 matrix:
cde
a123
b456
c789
Matrix Operations:
Various mathematical operations are performed on the matrices using the Roperators. The
result of the operation is also a [Link] dimensions (number of rows and columns) should
be same for the matrices involved in the operation.
Apply function to each column of matrix in R :
The function 'apply()' is used to apply the function to each column of the matrix. By using
these methods provided by R, it is easy to apply the function. The method to apply the
function to each column of the matrix is
This method is used to apply the function to each column of the matrix. The syntax is as
follows
apply(X, MARGIN, FUN)
Where:
X: Name of the matrix or data frame.
MARGIN: Dimension to operate across. Use 1 for row, 2 for column.
FUN: The function to apply.
In the below example, we calculated mean of each column by using the function apply().
a=c(12,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47)
#creating matrix
mat = matrix(a, nrow=3)
print("original matrix")
print(mat)
print("Applying function to each column for calculating mean")
result = apply(mat, 2, mean)
print(result)
Output:
[1] "original matrix"
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 12 19 25 31 37 43
[2,] 15 21 27 33 39 45
[3,] 17 23 29 35 41 47
[1] "Applying function to each column for calculating mean"
[1] 14.66667 21.00000 27.00000 33.00000 39.00000 45.00000
Apply function to each row in Data table in R :
For applying a function to each row of the given [Link], the user needs to call
the apply() function which is the base function of R programming language, and
pass the required parameter to this function to be applied in each row of the given
[Link] in R language.
apply() function returns a vector or array or list of values obtained by applying a
function to the margins of an array or matrix.
Adding Rows and Columns in a Matrix :
To add a row in matrix you can use rbind() function and to add a column to matrix you can
use cbind() function.
Adding Row
Let's see below example on adding row in matrix
number <- matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
cat("Before inserting a new row:\n")
print(number)
new_row <- c(10, 11, 12)
A <- rbind(number[1, ], new_row, number[-1, ])
cat("\nAfter inserting a new row:\n")
print(number)
Output
Before inserting a new row:
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
After inserting a new row:
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,]...
Adding Column
Let's see below example on adding column in matrix
number <- matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
cat("Before adding a new column:\n")
print(number)
new_column <- c(10, 11, 12)
number <- cbind(number, new_column)
cat("\nAfter adding a new column:\n")
print(number)
Output
Before adding a new column:
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
After adding a new column:
new_column
[1,] 1 2 3 10
[2,] 4 5 6 1...
Deleting Rows and Columns of a Matrix
To delete a row or a column, first of all, you need to access that row or column
and then insert a negative sign before that row or column. It indicates that you
had to delete that row or column.
Row deletion
Let's see the example below on deleting a row in a matrix.
A = matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
cat("Before deleting the 2nd row\n")
print(A)
A = A[-2, ]
cat("After deleted the 2nd row\n")
print(A)
Output
Before deleting the 2nd row
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
After deleted the 2nd row
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 7 8 9
Column deletion
Let's see the example below on deleting a column in a matrix.
A = matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
cat("Before deleting the 2nd column\n")
print(A)
A = A[, -2]
cat("After deleted the 2nd column\n")
print(A)
Output
Before deleting the 2nd column
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
After deleted the 2nd column
[,1] [,2]
[1,] 1 3
[2,] 4 6
[3,] 7 9
Vector/Matrix Distinction :
Matrix is just a vector but with two additional attributes: the number
of rows and the number of columns. Here, we’ll take a closer look at
the vector nature of matrices. Consider this example:
> z <- matrix(1:8,nrow=4)
>z
[,1] [,2]
[1,] 1 5
[2,] 2 6
[3,] 3 7
[4,] 4 8
As z is still a vector, we can query its length:
> length(z)
[1] 8
But as a matrix, z is a bit more than a vector:
> class(z)
[1] "matrix"
> attributes(z)
$dim
[1] 4 2
Dimensionality Reduction Techniques in R
Step-by-step implementation of the principal component analysis using R programming
language, applications of the principal component analysis in different fields, and its
advantages and disadvantages. Before discussing the principal component analysis, we
discuss a few pre-requisite topics related to the principal component analysis.
What is Dimensionality Reduction ?
Dimension reduction is the process of reducing the number of dimensions and reducing the
variable available by considering a few essential features. It can also defined as the technique
that converts the large-dimension dataset to the small-dimension data set by considering the
essential features. The dimensions reduction technique is mainly used when we are dealing
with a large amount of data set. The few methods in dimension reduction are principal
component analysis, wavelet transforms, singular value decomposition, linear discriminant
analysis, generalized discriminant analysis, and many more.
What is Principal Component Analysis ?
Principal component analysis is a useful and an important method for the dimensionality
reduction in the data pre processing . Principal Component analysis is served as a
unsupervised dimensionality reduction technique . In the principal component analysis we
almost consider the variance of the data points , without considering the other class labels .
We reduce the data based on the variance of the data points without considering the other
class labels or dependent variable in the provided information .
Steps in Principal Component Analysis
These are the few steps in principal component analysis
1. Standardization of the data of the given input data.
2. Calculation of the covariance matrix for the standardized data.
3. Calculating the eigen values and eigen vectors for the covariance matrix.
4. Sorting the eigen values and eigen vectors .
5. Identify the principal components and create a feature for the data.
6. Project the data on to the principal component axes.
Example of Principal Component Analysis
In this section , we discuss an example how to solve the principal component analysis
mathematically.
Let us take the data matrix as a=[1 4
25
3 6]
Now let us standardize the matrix by calculating the mean for the each column and
subtracting the each data point from the mean of the each column.
Implementation of the principle component analysis using R
Step-1 : Loading the input data
In order to implement the principle component analysis for dimension reduction using R ,
firstly we need the input data . In this example we are going to use the iris data set which
have the 150 rows and 5 columns. In iris data set the last column has the class label shows
the type of species.
data(iris)
summary(iris)
In the above code we just loaded the input data by using the function [Link]() and stored
in the variable mydata, in the second line we just printed the stored data and finally we used
a summary() function to print the summary of the [Link] know more about the summary
and [Link]() we can refer to the link provided summary() and [Link]() .
Step - 2 : Standardization of the data of the given input data
Standardization of data is the process of converting the data point to common format ,
which makes the data analyzing process easy. In this standardization process we used the
process scaling to reduce the last column of the mydata . Let us now look at the code in r
programming to remove the last row of the iris data which is class label which determines
the type of species .
#standardization of the data and printing it
standardizedmydata<-scale(iris[, 1:4])
head(standardizedmydata)
In the above code we just made the data set standardized . We have removed last row
of the mydata as we are the working with unsupervised principal component analysis ,
as the usupervised techniques does not require the class [Link] the above we just
used the scale() function . Sacle() is a function which is a built in R function which is
used for the scaling and centering the values of a [Link] know more about the
scale() function we can refer to the link provided scale() function .
Step - 3 : Covariance matrix calculation
Covariance matrix is a matrix of values of covariance between pair of elements of a random
sample . Covariance matrix is a square matrix . We know that the principal component
analysis uses the variance as a main consideration , we are calculating the covariance
matrix . Let us look at the R programming code for the calculation of the covariance matrix.
#Calculation of the covariance matrix
covariancematrix<-cov(standardizedmydata)
covariancematrix
In the above code we just created the covariance matrix and stored in the variable
covarincematrix and in the next line of the code we just printed the covarince [Link] the
code we have used the function cov() for the calculation of the covariance matrix . cov()
function is a built in R programming function for the calculation of the covariance matrix.
To know ore about the cov() function we can refer to the link provided cov() .
Step - 4 : Calculating the eigen values and eigen vectors
Eigen values are the scalar values which are associated with the set of linear equations in
linear transformation. Eigen vector is a vector of scalar values which are also called as
characteristic values . Let us now look at the code for the calculation of eigen values and
eigen vectors .
#calculating the eigen values and vectors
eigenvaluesvector<-eigen(covariancematrix)
eigenvaluesvector
In the above code we have used the eigen() function to calculate the eigen values and
eigen vectors . Eigen() is a built in function in R programming to calculate the eigen
values and eigen vectors of the given matrix.
Step - 5 : Sorting the eigen values and eigen vectors
In the below code we are just sorting the eigen values and eigen vectors by using the
function order . Order() is also a built in function that arranges the provided data in
the form of ascending or descending order .
#sorting the eigen values and eigen vectors
sortindice<-order(eigenvaluesvector$values,decreasing=TRUE)
sorteigenvalues<-eigenvaluesvector$values[sortindice]
sorteigenvector<-eigenvaluesvector$vectors[,sortindice]
sorteigenvalues
sorteigenvector
Step - 6 : Select principal components and project on to the data
In this step we are going to select the principal components and reducing the data as per the
selected principal components. Let us look at the code for it .
#selecting the principle components
principalcomponent<-2
selectedcomponents<-sorteigenvector[,1:principalcomponent]
selectedcomponents
#reduced data
reduceddata<-standardizedmydata %*% selectedcomponents
reduceddata
Step - 7 : Interpreting the results
In this step we are going to plot the principal component analysis graphs using the plot
function.
# Proportion of variance explained by each principal component
eigenvaluesvector$values / sum(eigenvaluesvector$values)
#plot1
plot(eigenvaluesvector$values, type = "o", main = "Plot1",
xlab = "Principal Component", ylab = "Eigenvalue")
Visualization of reduced dimensional data
# Visualization of reduced dimensional data
plot(reduceddata, col = iris$Species, pch = 16,
main = "Principle Component Analysis Visualization")
Higher dimensional Array in R
Arrays are the R data objects which can store data in more than two dimensions. For
example: If we create an array of dimensions (2, 3, 4) then it creates 4 rectangular matrices
each with 2 rows and 3 columns. These types of arrays are called Multidimensional Arrays.
Arrays can store only data types.
Creating a Multidimensional Array
An array is created using the array() function. It takes vectors as input and uses the
values in the dim parameter to create an array. A multidimensional array can be
created by defining the value of 'dim' argument as the number of dimensions that are
required.
Syntax:
MArray = array(c(vec1, vec2), dim)
Examples:
# Create two vectors of different lengths.
vector1 <- c(5, 9, 3)
vector2 <- c(10, 11, 12, 13, 14, 15)
# Take these vectors as input to the array.
result <- array(c(vector1, vector2), dim = c(3, 3, 2))
print(result)
Output:
,,1
[,1] [,2] [,3]
[1,] 5 10 13
[2,] 9 11 14
[3,] 3 12 15
,,2
[,1] [,2] [,3]
[1,] 5 10 13
[2,] 9 11 14
[3,] 3 12 15
Naming Columns and Rows
We can give names to the rows, columns, and matrices in the array by using
the dimnames parameter. Example:
# Create two vectors of different lengths.
vector1 <- c(5, 9, 3)
vector2 <- c(10, 11, 12, 13, 14, 15)
[Link] <- c("COL1", "COL2", "COL3")
[Link] <- c("ROW1", "ROW2", "ROW3")
[Link] <- c("Matrix1", "Matrix2")
# Take these vectors as input to the array.
result <- array(c(vector1, vector2), dim = c(3, 3, 2),
dimnames = list([Link], [Link],
[Link]))
print(result)
Output:
, , Matrix1
COL1 COL2 COL3
ROW1 5 10 13
ROW2 9 11 14
ROW3 3 12 15
, , Matrix2
COL1 COL2 COL3
ROW1 5 10 13
ROW2 9 11 14
ROW3 3 12 15
R-Lists
A list in R programming is a generic object consisting of an ordered collection of objects.
Lists are one-dimensional, heterogeneous data structures. The list can be a list of vectors,
a list of matrices, a list of characters, a list of functions, and so on. A list in R is created
with the use of the list() function.
R allows accessing elements of an R list with the use of the index value. In R, the indexing
of a list starts with 1 instead of 0.
1. Creating a List
To create a List in R you need to use the function called "list()". We want to build a list of
employees with the details. So for this, we want attributes such as ID, employee name, and
the number of employees.
Example:
empId = c(1, 2, 3, 4)
empName = c("Debi", "Sandeep", "Subham", "Shiba")
numberOfEmp = 4
empList = list(empId, empName, numberOfEmp)
print(empList)
Output
[[1]]
[1] 1 2 3 4
[[2]]
[1] "Debi" "Sandeep" "Subham" "Shiba"
[[3]]
[1] 4
General list operations
Naming the elements of a list
Name can be assigned to the elements of the list and those names can be used to access the
elements.
# Creating a List
Geek_list <- list(c("Geeks", "For", "Geeks"),
matrix(c(1:9), nrow = 3),
list("Geek", 12.3))
# Naming each element of the list
names(Geek_list) <- c("This_is_a_vector",
"This_is_a_Matrix",
"This_is_a_listwithin_the_list")
# Printing the list
print(Geek_list)
Output:
$This_is_a_vector
[1] "Geeks" "For" "Geeks"
$This_is_a_Matrix
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
$This_is_a_listwithin_the_list
$This_is_a_listwithin_the_list[[1]]
[1] "Geek"
$This_is_a_listwithin_the_list[[2]]
[1] 12.3
Adding, Deleting, and Updating elements of a list
In R, a new element can be added to the list, the existing element can be deleted or updated.
# Creating a List
Geek_list <- list(c("Geeks", "For", "Geeks"),
matrix(c(1:9), nrow = 3),
list("Geek", 12.3))
# Naming each element of the list
names(Geek_list) <- c("This_is_a_vector",
"This_is_a_Matrix",
"This_is_a_listwithin_the_list")
# To add a new element.
Geek_list[4] <- "New element"
print(Geek_list)
# To remove the last element.
Geek_list[4] <- NULL
# To print the 4th Element.
print(Geek_list[4])
# To update the 3rd Element.
Geek_list[3] <- "updated element"
print(Geek_list[3])
Output:
$This_is_a_vector
[1] "Geeks" "For" "Geeks"
$This_is_a_Matrix
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
$This_is_a_listwithin_the_list
$This_is_a_listwithin_the_list[[1]]
[1] "Geek"
$This_is_a_listwithin_the_list[[2]]
[1] 12.3
[[4]]
[1] "New element"
$
NULL
$This_is_a_listwithin_the_list
[1] "updated element"
Accessing elements of a List
In order to access the list elements, use the index number, and in case of named list,
elements can be accessed using its name also.
# Creating a List
Geek_list <- list(c("Geeks", "For", "Geeks"),
matrix(c(1:9), nrow = 3),
list("Geek", 12.3))
# Naming each element of the list
names(Geek_list) <- c("This_is_a_vector",
"This_is_a_Matrix",
"This_is_a_listwithin_the_list")
# To access the first element of the list.
print(Geek_list[1])
# To access the third element.
print(Geek_list[3])
# To access the list element using the name of the element.
print(Geek_list$This_is_a_Matrix)
Output:
$This_is_a_vector
[1] "Geeks" "For" "Geeks"
$This_is_a_listwithin_the_list
$This_is_a_listwithin_the_list[[1]]
[1] "Geek"
$This_is_a_listwithin_the_list[[2]]
[1] 12.3
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
Applying functions to lists
lapply() function in R Programming Language is used to apply a function over a list of
elements.
lapply() function is used with a list and performs the following operations:
lapply(List, length): Returns the length of objects present in the list, List.
lapply(List, sum): Returns the sum of elements held by objects in the list, List.
lapply(List, mean): Returns the mean of elements held by objects in the list, List.
lapply(List, cumsum): Returns the cumulative sum of elements held by objects present
inside the list, List.
Syntax: lapply(list, func)
Parameters:
list: list of elements
Example 1: Basic example of lapply() Function in R programming
# R program to illustrate
# lapply() function
# Creating a matrix
A = matrix(1:9, 3, 3)
# Creating another matrix
B = matrix(10:18, 3, 3)
# Creating a list
myList = list(A, B)
# applying lapply()
determinant = lapply(myList, det)
print(determinant)
Output:
[[1]]
[1] 0
[[2]]
[1] 5.329071e-15
Recursively apply a Function to a List in R Programming - rapply()
function
rapply() function in R Language is used to recursively apply a function to a list.
Syntax: rapply(object, f, classes = "ANY", deflt = NULL, how = c("unlist", "replace",
"list"))
Parameters: object: represents list or an expression
f: represents function to be applied recursively
classes: represents class name of the vector or "ANY" to match any of the class
deflt: represents default result when how is not "replace"
how: represents modes
The modes in rapply() function are of 2 basic types. If how = "replace", each element of
the list object which is not itself is a list and has a class included in classes then each
element of the list is replaced by the resulting value of the function f applied to the element.
If how = "list" or how = "unlist", list object is copied and all non-list elements which are
included in classes are replaced by the resulting value of the function f applied to the
element and all other are replaced by deflt.
Example 1: Using replace mode
# Defining a list
ls <- list(a = 1:5, b = 100:110, c = c('a', 'b', 'c'))
# Print whole list
cat("Whole List: \n")
print(ls)
# Using replace mode
cat("Using replace mode:\n")
rapply(ls, mean, how = "replace", classes = "integer")
Output:
Whole List:
$a
[1] 1 2 3 4 5
$b
[1] 100 101 102 103 104 105 106 107 108 109 110
$c
[1] "a" "b" "c"
Using replace mode:
$a
[1] 3
$b
[1] 105
$c
[1] "a" "b" "c"
Example 2: Using list mode
# Defining a list
ls <- list(a = 1:5, b = 100:110, c = c('a', 'b', 'c'))
# Print whole list
cat("Whole List: \n")
print(ls)
# Using list mode
cat("Using list mode:\n")
rapply(ls, mean, how = "list", classes = "integer")
Output:
Whole List:
$a
[1] 1 2 3 4 5
$b
[1] 100 101 102 103 104 105 106 107 108 109 110
$c
[1] "a" "b" "c"
Using list mode:
$a
[1] 3
$b
[1] 105
$c
NULL