Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.
D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
R Programming
UNIT III Matrices, Arrays and Data Frames
R Matrices: -
Matrices are the R objects in which the elements are arranged in a two-dimensional rectangular
layout. They contain elements of the same atomic types. Though we can create a matrix
containing only characters or only logical values, they are not of much use. We use matrices
containing numeric elements to be used in mathematical calculations.
A Matrix is created using the matrix() function.
Syntax:-
The basic syntax for creating a matrix in R is –
matrix(data, nrow, ncol, byrow, dimnames)
Following is the description of the parameters used −
data is the input vector which becomes the data elements of the matrix.
nrow is the number of rows to be created.
ncol is the number of columns to be created.
byrow is a logical clue. If TRUE then the input vector elements are arranged by row.
dimname is the names assigned to the rows and columns.
Example:-
Create a matrix taking a vector of numbers as input.
# Elements are arranged sequentially by row.
M <- matrix(c(3:14), nrow = 4, byrow = TRUE)
print(M)
# Elements are arranged sequentially by column.
N <- matrix(c(3:14), nrow = 4, byrow = FALSE)
print(N)
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
# Define the column and row names.
rownames = c("row1", "row2", "row3", "row4")
colnames = c("col1", "col2", "col3")
P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames))
print(P)
Output: -
[,1] [,2] [,3]
[1,] 3 4 5
[2,] 6 7 8
[3,] 9 10 11
[4,] 12 13 14
[,1] [,2] [,3]
[1,] 3 7 11
[2,] 4 8 12
[3,] 5 9 13
[4,] 6 10 14
col1 col2 col3
row1 3 4 5
row2 6 7 8
row3 9 10 11
row4 12 13 14
Accessing Elements of a Matrix:-
Elements of a matrix can be accessed by using the column and row index of the element. We
consider the matrix P above to find the specific elements below.
Live Demo
# Define the column and row names.
rownames = c("row1", "row2", "row3", "row4")
colnames = c("col1", "col2", "col3")
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
# Create the matrix.
P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames))
# Access the element at 3rd column and 1st row.
print(P[1,3])
# Access the element at 2nd column and 4th row.
print(P[4,2])
# Access only the 2nd row.
print(P[2,])
# Access only the 3rd column.
print(P[,3])
Output: -
[1] 5
[1] 13
col1 col2 col3
6 7 8
row1 row2 row3 row4
5 8 11 14
Matrix Operations: -
Various mathematical operations are performed on the matrices using the R operators. The result
of the operation is also a matrix.
The dimensions (number of rows and columns) should be same for the matrices involved in the
operation.
1) Matrix Addition & Subtraction:-
# Create two 2x3 matrices.
matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2)
print(matrix1)
matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2)
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
print(matrix2)
# Add the matrices.
result <- matrix1 + matrix2
cat("Result of addition","\n")
print(result)
# Subtract the matrices
result <- matrix1 - matrix2
cat("Result of subtraction","\n")
print(result)
Output: -
[,1] [,2] [,3]
[1,] 3 -1 2
[2,] 9 4 6
[,1] [,2] [,3]
[1,] 5 0 3
[2,] 2 9 4
Result of addition
[,1] [,2] [,3]
[1,] 8 -1 5
[2,] 11 13 10
Result of subtraction
[,1] [,2] [,3]
[1,] -2 -1 -1
[2,] 7 -5 2
2) Matrix Multiplication & Division:-
Live Demo
# Create two 2x3 matrices.
matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2)
print(matrix1)
matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2)
print(matrix2)
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
# Multiply the matrices.
result <- matrix1 * matrix2
cat("Result of multiplication","\n")
print(result)
# Divide the matrices
result <- matrix1 / matrix2
cat("Result of division","\n")
print(result)
Output: -
[,1] [,2] [,3]
[1,] 3 -1 2
[2,] 9 4 6
[,1] [,2] [,3]
[1,] 5 0 3
[2,] 2 9 4
Result of multiplication
[,1] [,2] [,3]
[1,] 15 0 6
[2,] 18 36 24
Result of division
[,1] [,2] [,3]
[1,] 0.6 -Inf 0.6666667
[2,] 4.5 0.4444444 1.5000000
Matrix Transpose (Transpose of Matrix): -
Transpose of a matrix is an operation in which we convert the rows of the matrix in column
and column of the matrix in rows. The general equation for performing the transpose of a
matrix is as follows.
Aij = Aji where i is not equal to j
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)
# R program for Transpose of a Matrix
Assistant Professor
# create a matrix with 2 rows
# using matrix() method Karmaveer Bhaurao Patil College, Urun Islampur
M <- matrix(1:6, nrow = 2)
# print the original matrix
print(M)
# transpose of matrix
# using t() function.
t <- t(M)
Example: -
Matrix M ---> [1, 8, 9
12, 6, 2
19, 42, 3]
Transpose of M
Output ---> [1, 12, 19
8, 6, 42,
9, 2, 3]
Transpose of a Matrix can be performed in two ways:
1) Finding the transpose by using the t() function:-
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
# print the transpose matrix
print(t)
Output: -
[, 1] [, 2] [, 3]
[1, ] 1 3 5
[2, ] 2 4 6
[, 1] [, 2]
[1, ] 1 2
[2, ] 3 4
[3, ] 5 6
2) By iterating over each value using Loops: -
# create matrix with 3 rows and 3 columns
Matrix = matrix(1:9, nrow = 3)
# print the matrix
print(Matrix)
# create another matrix
M2 = Matrix
# Loops for Matrix Transpose
for (i in 1:nrow(M2))
{
# iterate over each row
for (j in 1:ncol(M2))
{
# iterate over each column
# assign the correspondent elements
# from row to column and column to row.
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
M2[i, j] <- Matrix[j, i]
}
}
# print the transposed matrix
print(M2)
Output: -
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
R – Arrays:-
Arrays are the R data objects which can store data in more than two dimensions. For example −
If we create an array of dimension (2, 3, 4) then it creates 4 rectangular matrices each with 2
rows and 3 columns. Arrays can store only data type.
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.
Example:-
The following example creates an array of two 3x3 matrices each with 3 rows and 3 columns.
Live Demo
# Create two vectors of different lengths.
vector1 <- c(5,9,3)
vector2 <- c(10,11,12,13,14,15)
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
# 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
Accessing Array Elements:-
Live Demo
# 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 the third row of the second matrix of the array.
print(result[3,,2])
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
# Print the element in the 1st row and 3rd column of the 1st matrix.
print(result[1,3,1])
# Print the 2nd Matrix.
print(result[,,2])
Output: -
COL1 COL2 COL3
3 12 15
[1] 13
COL1 COL2 COL3
ROW1 5 10 13
ROW2 9 11 14
ROW3 3 12 15
Calculations Across Array Elements:-
We can do calculations across the elements in an array using the apply() function.
Syntax:-
apply(x, margin, fun)
Following is the description of the parameters used −
x is an array.
margin is the name of the data set used.
fun is the function to be applied across the elements of the array.
Example:-
We use the apply() function below to calculate the sum of the elements in the rows of an array
across all the matrices.
Live Demo
# Create two vectors of different lengths.
vector1 <- c(5,9,3)
vector2 <- c(10,11,12,13,14,15)
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
# Take these vectors as input to the array.
[Link] <- array(c(vector1,vector2),dim = c(3,3,2))
print([Link])
# Use apply to calculate the sum of the rows across all the matrices.
result <- apply([Link], c(1), sum)
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
[1] 56 68 60
R - Data Frames: -
A data frame is a table or a two-dimensional array-like structure in which each column contains
values of one variable and each row contains one set of values from each column.
Following are the characteristics of a data frame.
The column names should be non-empty.
The row names should be unique.
The data stored in a data frame can be of numeric, factor or character type.
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
Each column should contain same number of data items.
Create Data Frame:-
Live Demo
# Create the data frame.
[Link] <- [Link](
emp_id = c (1:5),
emp_name = c("Rick","Dan","Michelle","Ryan","Gary"),
salary = c(623.3,515.2,611.0,729.0,843.25),
start_date = [Link](c("2012-01-01", "2013-09-23", "2014-11-15", "2014-05-11",
"2015-03-27")),
stringsAsFactors = FALSE
)
# Print the data frame.
print([Link])
Output: -
1 1 Rick 623.30 2012-01-01
2 2 Dan 515.20 2013-09-23
3 3 Michelle 611.00 2014-11-15
4 4 Ryan 729.00 2014-05-11
5 5 Gary 843.25 2015-03-27
Basic operations on data frames: -
Data Frames are generic data objects of R which are used to store the tabular data. Data
frames are considered to be the most popular data objects in R programming because it is more
comfortable to analyze the data in the tabular form. Data frames can also be taught as
mattresses where each column of a matrix can be of the different data types. Data Frame are
made up of three principal components, the data, rows, and columns.
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
Operations that can be performed on a Data Frame are:
1) Creating a Data Frame
2) Accessing rows and columns
3) Selecting the subset of the data frame
4) Editing data frames
5) Adding extra rows and columns to the data frame
6) Add new variables to data frame based on existing ones
7) Delete rows and columns in a data frame
1) Creating a Data Frame: -
R program to illustrate dataframe
# A vector which is a character vector
Name = c("Amiya", "Raj", "Asish")
# A vector which is a character vector
Language = c("R", "Python", "Java")
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
# A vector which is a numeric vector
Age = c(22, 25, 45)
# To create dataframe use [Link] command and
# then pass each of the vectors
# we have created as arguments
# to the function [Link]()
df = [Link](Name, Language, Age)
print(df)
Output: -
Name Language Age
1 Amiya R 22
2 Raj Python 25
3 Asish Java 45
2) Accessing rows and columns: -
# R program to illustrate operations
# on a data frame
# Creating a dataframe
df = [Link](
"Name" = c("Amiya", "Raj", "Asish"),
"Language" = c("R", "Python", "Java"),
"Age" = c(22, 25, 45)
)
print(df)
# Accessing first and second row
cat("Accessing first and second row\n")
print(df[1:2, ])
Output: -
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
Name Language Age
1 Amiya R 22
2 Raj Python 25
3 Asish Java 45
Accessing first and second row
Name Language Age
1 Amiya R 22
2 Raj Python 25
3) Selecting the subset of the data frame: -
# R program to illustrate operations
# on a data frame
# Creating a dataframe
df = [Link](
"Name" = c("Amiya", "Raj", "Asish"),
"Language" = c("R", "Python", "Java"),
"Age" = c(22, 25, 45)
)
print(df)
# Selecting the subset of the data frame
# where Name is equal to Amiya
# OR age is greater than 30
newDf = subset(df, Name =="Amiya"|Age>30)
cat("After Selecting the subset of the data frame\n")
print(newDf)
Output: -
Name Language Age
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
1 Amiya R 22
2 Raj Python 25
3 Asish Java 45
After Selecting the subset of the data frame
Name Language Age
1 Amiya R 22
3 Asish Java 45
4) Editing data frames: -
# R program to illustrate operation on a data frame
# Creating a dataframe
df = [Link](
"Name" = c("Amiya", "Raj", "Asish"),
"Language" = c("R", "Python", "Java"),
"Age" = c(22, 25, 45)
)
cat("Before editing the dataframe\n")
print(df)
# Editing dataframes by direct assignments
# [[3]] accessing the top level components
# Here Age in this case
# [[3]][3] accessing inner level components
# Here Age of Asish in this case
df[[3]][3] = 30
cat("After edited the dataframe\n")
print(df)
Output: -
Before editing the data frame
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
Name Language Age
1 Amiya R 22
2 Raj Python 25
3 Asish Java 45
After edited the data frame
Name Language Age
1 Amiya R 22
2 Raj Python 25
4 Asish Java 30
5) Adding extra rows and columns to the data frame:-
# R program to illustrate operation on a data frame
# Creating a dataframe
df = [Link](
"Name" = c("Amiya", "Raj", "Asish"),
"Language" = c("R", "Python", "Java"),
"Age" = c(22, 25, 45)
)
cat("Before adding row\n")
print(df)
# Add a new row using rbind()
newDf = rbind(df, [Link](Name = "Sandeep",
Language = "C",
Age = 23
))
cat("After Added a row\n")
print(newDf)
Output: -
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
Before adding row
Name Language Age
1 Amiya R 22
2 Raj Python 25
3 Asish Java 45
After Added a row
Name Language Age
1 Amiya R 22
2 Raj Python 25
3 Asish Java 45
5 Sandeep C 23
6) Add new variables to data frame based on existing ones:-
# R program to illustrate operation on a data frame
# Importing the dplyr library
library(dplyr)
# Creating a dataframe
df = [Link](
"Name" = c("Amiya", "Raj", "Asish"),
"Language" = c("R", "Python", "Java"),
"Age" = c(22, 25, 45)
)
cat("Original Dataframe\n")
print(df)
# Creating an extra variable column
# "log_Age" which is log of variable column "Age"
# Using mutate() command
newDf = mutate(df, log_Age = log(Age))
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
cat("After creating extra variable column\n")
print(newDf)
Output: -
Original Dataframe
Name Language Age
1 Amiya R 22
2 Raj Python 25
3 Asish Java 45
After creating extra variable column
Name Language Age log_Age
1 Amiya R 22 3.091042
2 Raj Python 25 3.218876
3 Asish Java 45 3.806662
7) Delete rows and columns in a data frame: -
# R program to illustrate operation on a data frame
# Creating a dataframe
df = [Link](
"Name" = c("Amiya", "Raj", "Asish"),
"Language" = c("R", "Python", "Java"),
"Age" = c(22, 25, 45)
)
cat("Before deleting the 3rd row and 2nd column\n")
print(df)
# delete the third row and the second column
newDF = df[-3, -2]
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)
Assistant Professor
Karmaveer Bhaurao Patil College, Urun Islampur
cat("After Deleted the 3rd row and 2nd column\n")
print(newDF)
Output: -
Before deleting the 3rd row and 2nd column
Name Language Age
1 Amiya R 22
2 Raj Python 25
3 Asish Java 45
After Deleted the 3rd row and 2nd column
Name Age
1 Amiya 22
2 Raj 25