📊 STATISTICS WITH R PROGRAMMING
Madurai Kamaraj University · II B.Sc. Mathematics, III Semester · TANSCHE Syllabus
ARO Study Circle
Chapter 3 · Matrices, Arrays, Factors, Data Frames and Graphical Analysis
Syllabus: Creating matrices – Creating Arrays – Creating factors – Creating Data Frames – Aggregating Data – Sorting Data – Merging Data – Reshaping data – Sub-setting data – Data Type Conversion – Bar charts – Histogram – Line graphs – Pie charts – Graphical analysis and summaries of Data using Descriptive Statistics
3.1 Matrices
A matrix is a collection of data elements arranged in a two-dimensional rectangular layout. Matrices contain elements of the same atomic type (numeric, character, logical, etc.). Matrices containing numeric elements are most useful for mathematical calculations.
3.1.1 Creating Matrices
Basic syntax: matrix(data, nrow, ncol, byrow, dimnames). If byrow = TRUE, elements are arranged by row.
# Elements arranged by row
M <- matrix(c(1:12), nrow = 4, byrow = TRUE)
M
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
[4,] 10 11 12
# Elements arranged by column
N <- matrix(c(1:12), nrow = 4, byrow = FALSE)
N
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
# Define column and row names
rnames <- c("r1", "r2", "r3", "r4")
cnames <- c("c1", "c2", "c3")
P <- matrix(c(1:12), nrow = 4, byrow = TRUE, dimnames = list(rnames, cnames))
P
c1 c2 c3
r1 1 2 3
r2 4 5 6
r3 7 8 9
r4 10 11 12
Using cbind() and rbind()
# Elements filled column-wise
M <- cbind(c(1,2,3), c(4,5,6))
M
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
# Elements filled row-wise
N <- rbind(c(1,2,3), c(4,5,6))
N
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
Using dim() Function
v <- c(1,2,3,4,5,6)
dim(v) <- c(2,3)
v
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
3.1.2 Accessing Matrix Elements
(a) Integer Vector as Index
M <- matrix(c(1:12), nrow = 4, byrow = TRUE)
M
M[2,3] # element at 2nd row, 3rd column
M[2,] # the 2nd row
M[,3] # the 3rd column
M[,] # entire matrix
M[,c(1,3)] # 1st and 3rd columns
M[c(3,2),] # 3rd and 2nd rows
M[c(1,2), c(2,3)] # 1st/2nd row, 2nd/3rd col
M[-1,] # all rows except first
[1] 6
[1] 4 5 6
[1] 3 6 9 12
... (full matrix)
[,1] [,2]
[1,] 1 3
[2,] 4 6
[3,] 7 9
[4,] 10 12
...
# Using drop = FALSE to preserve matrix structure
M[2, drop = FALSE]
[,1] [,2] [,3]
[1,] 4 5 6
(b) Logical Vector as Index
M <- matrix(c(1:12), nrow = 4, byrow = TRUE)
M[c(TRUE,FALSE,TRUE,FALSE), c(TRUE,TRUE,FALSE)]
[,1] [,2]
[1,] 1 2
[2,] 7 8
# Filtering elements
M[M > 4] # elements greater than 4
M[M %% 2 != 0] # odd elements
[1] 7 10 5 8 11 6 9 12
[1] 1 7 5 11 3 9
(c) Character Vector as Index
M <- matrix(c(1:12), nrow = 4, byrow = TRUE,
dimnames = list(c("r1","r2","r3","r4"),
c("c1","c2","c3")))
M["r2", "c3"] # element at 2nd row, 3rd column
M[TRUE, c("c1","c2")] # all rows, columns c1 and c2
[1] 6
c1 c2
r1 1 2
r2 4 5
r3 7 8
r4 10 11
3.1.3 Matrix Arithmetic
matrix1 <- matrix(c(10,20,30,40,50,60), nrow = 2, byrow = TRUE)
matrix2 <- matrix(c(1,2,3,4,5,6), nrow = 2, byrow = TRUE)
matrix1 + matrix2
matrix1 - matrix2
matrix1 * matrix2 # element-wise multiplication
matrix1 / matrix2 # element-wise division
[,1] [,2] [,3]
[1,] 11 33 55
[2,] 22 44 66
[,1] [,2] [,3]
[1,] 9 27 45
[2,] 18 36 54
[,1] [,2] [,3]
[1,] 10 90 250
[2,] 40 160 360
[,1] [,2] [,3]
[1,] 10 10 10
[2,] 10 10 10
3.1.4 Matrix Manipulation
matrix1 <- matrix(c(10,20,30,40,50,60), nrow = 3)
matrix1[2,2] <- 100
matrix1[matrix1 < 40] <- 0
cbind(matrix1, c(1,2,3))
rbind(matrix1, c(1,2))
matrix1 <- matrix1[1:2, ]
dim(matrix1) <- c(2,3)
[,1] [,2]
[1,] 0 40
[2,] 0 100
[3,] 0 60
[,1] [,2] [,3]
[1,] 0 40 1
[2,] 0 100 2
[3,] 0 60 3
...
3.1.5 Matrix Operations
(a) Matrix Multiplication
matrix1 <- matrix(c(10,20,30,40,50,60), nrow = 3) # 3x2
matrix2 <- matrix(c(1,2,3,4,5,6), nrow = 2) # 2x3
product <- matrix1 %*% matrix2
product
[,1] [,2] [,3]
[1,] 90 190 290
[2,] 120 260 400
[3,] 150 330 510
(b) Transpose
matrix1 <- matrix(c(10,20,30,40,50,60), nrow = 3)
t(matrix1)
[,1] [,2] [,3]
[1,] 10 20 30
[2,] 40 50 60
(c) Outer Product
matrix1 %o% matrix2
(6 matrices of 3x2 shown in console)
(d) Cross Product
A <- matrix(c(10,20,30,40), nrow = 2)
B <- matrix(c(1,2,3,4), nrow = 2)
crossprod(A, B)
crossprod(A)
[,1] [,2]
[1,] 50 110
[2,] 110 250
[,1] [,2]
[1,] 500 1100
[2,] 1100 2500
(e) Diagonal Matrix
A <- matrix(1:9, nrow = 3)
diag(A)
diag(3)
diag(c(1,2,3), 3)
[1] 1 5 9
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 2 0
[3,] 0 0 3
(f) Row Sum and Column Sum
rowSums(A)
colSums(A)
[1] 12 15 18
[1] 6 15 24
(g) Row Means and Column Means
rowMeans(A)
colMeans(A)
[1] 4 5 6
[1] 2 5 8
(h) Eigen Values and Eigen Vectors
A <- matrix(1:9, nrow = 3)
eigen(A)
$values [1] 1.611684e+01 -1.116844e+00 -5.700691e-16
$vectors ... (matrix)
(i) Inverse
A <- matrix(1:4, nrow = 2)
solve(A)
B <- matrix(1:2, nrow = 2)
solve(A, B)
[,1] [,2]
[1,] -2 1.5
[2,] 1 -0.5
[,1]
[1,] 1
[2,] 1
3.2 Arrays
Arrays are R data objects that can store data in more than two dimensions. Arrays can store only the same data type. For example, an array of dimension (2,4,5) creates 5 rectangular matrices each with 2 rows and 4 columns.
3.2.1 Creating Arrays
v1 <- c(1,2,3)
v2 <- c(10,20,30,40,50,60)
A <- array(c(v1, v2), dim = c(3,3,2))
A
, , 1
[,1] [,2] [,3]
[1,] 1 10 40
[2,] 2 20 50
[3,] 3 30 60
, , 2
[,1] [,2] [,3]
[1,] 1 10 40
[2,] 2 20 50
[3,] 3 30 60
3.2.2 Accessing Array Elements
A[1,2,1] # 1st row, 2nd column in matrix 1
A[3,4,2] # 3rd row, 4th column in matrix 2 (if dims allow)
3.2.3 Array Element Manipulation using apply()
# Row sum of all matrices
B <- apply(A, c(1), sum)
B
# Column sum of all matrices
C <- apply(A, c(2), sum)
C
[1] 102 144 186
[1] 12 120 300
3.2.4 Array Arithmetic
mat.A <- A[,,1]
mat.B <- A[,,2]
mat.A + mat.B
mat.A - mat.B
mat.A * mat.B
mat.A / mat.B
3.3 Factors
Factor is a data structure used for fields that take only predefined, finite number of values. They are used to categorize data and store it as levels.
3.3.1 Creating Factors
x <- factor(c("single", "married", "married", "single", "divorced"))
x
class(x)
levels(x)
str(x)
[1] single married married single divorced
Levels: divorced married single
[1] "factor"
[1] "divorced" "married" "single"
Factor w/ 3 levels "divorced","married",..: 3 2 2 3 1
3.3.2 Accessing Factor Components
x[3]
x[c(2,4)]
x[-1]
x[c(TRUE, FALSE, FALSE, TRUE, FALSE)]
3.3.3 Modifying Factors
x[2] <- "divorced"
levels(x) <- c(levels(x), "widowed")
x[3] <- "widowed"
gl(3, 2, labels = c("single", "married", "divorced"))
3.4 Data Frames
A data frame is used for storing data tables. It is a list of vectors of equal length. Each column contains values of one variable and each row contains one set of values from each column.
3.4.1 Creating Data Frames
x <- data.frame("roll" = 1:2, "name" = c("Jack","Jill"), "age" = c(20,22))
x
names(x)
nrow(x)
ncol(x)
str(x)
summary(x)
roll name age
1 1 Jack 20
2 2 Jill 22
[1] "roll" "name" "age"
[1] 2
[1] 3
'data.frame': 2 obs. of 3 variables ...
3.4.2 Accessing Data Frame Components
x$name
x[["name"]]
x[[3]]
x["name"]
x[1:2,]
x[,2:3]
x[c(1,2), c(2,3)]
x[-1]
x[-1,]
x[x$age > 21,]
head(x, 2)
3.4.3 Modifying Data Frames
x[1, "age"] <- 25
xbloodgroup <- c("A+", "B-", "AB+")
x <- cbind(x, city = c("Delhi", "Mumbai", "Chennai"))
x <- rbind(x, c(4, "Jack", 24, "B+", "Delhi"))
3.4.4 Aggregating Data
y <- data.frame(roll = 1:11, name = c("Jack","Jill","Jeeva","Smith","Bob","Smith","John","Mathew","Charles","Zen","Yug"),
age = c(20,20,30,21,19,21,19,18,22,25,21),
marks = c(100,98,99,75,80,90,88,43,87,43,89))
aggregate(y$ marks, list(age = y$age), mean)
aggregate(y$ marks, list(age = y$age), max)
aggregate(y$ marks, list(age = y$age), sum)
3.4.5 Sorting Data
newdata <- x[order(x$name),]
newdata <- x[order(x$age, x$name),]
newdata <- x[order(x$name, -x$age),]
3.4.6 Merging Data
df1 <- data.frame(CustomerId = c(1:6), Product = c(rep("Toaster",3), rep("Radio",3)))
df2 <- data.frame(CustomerId = c(2,4,6), State = c(rep("Alabama",2), rep("Ohio",1)))
merge(df1, df2, by = "CustomerId") # inner
merge(df1, df2, by = "CustomerId", all = TRUE) # outer
merge(df1, df2, by = "CustomerId", all.x = TRUE) # left
merge(df1, df2, by = "CustomerId", all.y = TRUE) # right
merge(df1, df2, by = NULL) # cross
3.4.7 Reshaping Data
library(reshape2)
mdata <- melt(y, id = c("id","age"))
markmeans <- dcast(mdata, id ~ variable, mean)
agemeans <- dcast(mdata, age ~ variable, mean)
3.4.8 Subsetting Data
newdata <- subset(x, age >= 25 & age < 30, select = c(roll, name, age))
newdata <- subset(x, name == "Smith" | name == "John", select = roll:age)
3.5 Data Type Conversion
| to vector | to matrix | to data frame |
| from vector | c(x,y) | cbind(x,y), rbind(x,y) | data.frame(x,y) |
| from matrix | as.vector(x) | — | as.data.frame(mymatrix) |
| from data frame | — | as.matrix(myframe) | — |
x <- 10.5
as.integer(x); as.character(x); as.complex(x); as.logical(x)
vec <- 1:6; mat <- matrix(vec, nrow = 2); as.vector(mat)
df <- as.data.frame(mat); as.matrix(df)
3.6 Bar Charts
A bar chart represents data in rectangular bars with length of the bar proportional to the value of the variable.
max.temp <- c(22, 27, 26, 24, 23, 26, 28)
barplot(max.temp)
3.6.1 Vertical Bar Charts
B <- c(3, 2, 25, 35, 22, 34, 19)
png(file = "Mybarchart.png", width = 800, height = 600)
barplot(B, main = "MY NEW BARPLOT", xlab = "LETTERS", ylab = "MY VALUES",
names.arg = c("A","B","C","D","E","F","G"),
col = "yellow", border = "red",
density = c(90,70,50,40,30,20,10))
text(x = 1:length(B), y = B, labels = B, pos = 3, cex = 0.9, col = "black")
dev.off()
3.6.2 Plotting Bars Horizontally
max.temp <- c(22, 27, 26, 24, 23, 26, 30)
barplot(max.temp, main = "Maximum Temperatures in a Week",
xlab = "Degree Celsius", ylab = "Day",
names.arg = c("Sun","Mon","Tue","Wed","Thu","Fri","Sat"),
col = "lightgreen", horiz = TRUE)
3.6.3 Plotting Categorical Data
age <- c(17,18,18,17,18,19,18,16,18,18)
barplot(table(age), main = "Age Count of 10 Students",
xlab = "Age", ylab = "Count", border = "blue", col = "orange")
3.6.4 Grouped Bar Chart
A <- matrix(c(3,5,7,1,9,4,6,5,2,12,2,1,7,6,8), nrow = 3, ncol = 5, byrow = TRUE)
b <- barplot(A, main = "Total Revenue by Department", beside = TRUE,
names.arg = c("Jan","Feb","Mar","Apr","May"),
xlab = "Month", ylab = "Revenue (in 1000)",
col = c("tan2","blue","darkslategray3"))
legend("topleft", c("Software","Hardware","Service"), fill = c("tan2","blue","darkslategray3"), cex = 0.8)
text(b, A, labels = A, pos = 3, cex = 0.8, xpd = TRUE)
3.6.5 Stacked Bar Chart
b <- barplot(A, main = "Departmental Revenue Contributions",
names.arg = c("Jan","Feb","Mar","Apr","May"),
xlab = "Quarter", ylab = "Revenue(in 1000)",
col = c("red","green","yellow"), ylim = c(0, max(colSums(A))+5))
legend("topleft", legend = c("Software","Hardware","Service"), fill = c("red","green","yellow"), cex = 0.8)
text(b, A[1,]/2, labels = A[1,], cex = 0.8)
text(b, A[1,]+A[2,]/2, labels = A[2,], cex = 0.8)
text(b, colSums(A)-A[3,]/2, labels = A[3,], cex = 0.8)
3.7 Histograms
Histograms display continuous data ranges on the x‑axis, use bins to group data points, and show frequency or density on the y‑axis.
wages <- c(400,700,200,700,400,600,500,400,500,600,700,300,600,700,400,300)
hist(wages, main = "Daily Wage Distribution", xlab = "Wage Amount (Rupees)",
ylab = "Number of Workers", col = "lightgreen", border = "darkgreen", xlim = c(200,800))
3.7.2 Histogram Attributes
h <- hist(wages)
h
$breaks [1] 200 300 400 500 600 700
$counts [1] 3 4 2 3 4
$density [1] 0.001875 0.002500 0.001250 0.001875 0.002500
$mids [1] 250 350 450 550 650
3.7.3 Labeled Histograms
h <- hist(wages, main = "Daily Wage Distribution", xlab = "Wage Amount (Rupees)",
ylab = "Number of Workers", col = "goldenrod", border = "darkred", ylim = c(0,5))
text(h$mids, h$counts, labels = h$counts, pos = 3, col = "red", cex = 0.8)
3.7.4 Histogram with Breaks
hist(wages, breaks = 10, main = "Fixed Bins (10)")
hist(wages, breaks = 40, main = "Fixed Bins (40)")
hist(wages, breaks = c(200,350,450,550,650,780), main = "Manual Breaks")
3.7.5 Histograms with Density Lines
h <- hist(wages, main = "Daily Wages", xlab = "Wages in Rupees",
ylab = "Density", col = "yellow", freq = FALSE)
lines(density(wages), col = "red", lwd = 2)
3.8 Line Graphs
A line chart connects a series of points by drawing line segments between them, useful for identifying trends.
months <- 1:5
rainfall <- c(12,15,14,18,20)
plot(months, rainfall, type = "o", main = "Rainfall Trends",
xlab = "Month", ylab = "Rainfall (mm)", col = "royalblue",
lty = 1, lwd = 2, pch = 19, cex = 1.2, xlim = c(1,5.5), las = 1)
grid()
3.8.2 Graphs with Multiple Lines
kerala <- c(14,12,13,10,15)
goa <- c(15,10,11,15,12)
assam <- c(10,13,11,12,14)
plot(months, kerala, type = "o", col = "red", ylim = c(5,20),
main = "Regional Rainfall", xlab = "Month", ylab = "Rainfall (mm)", lwd = 2)
lines(months, goa, type = "o", col = "blue", lwd = 2)
lines(months, assam, type = "o", col = "green", lwd = 2)
legend("topright", legend = c("Kerala","Goa","Assam"), col = c("red","blue","green"), lty = 1)
3.9 Pie Charts
3.9.1 A Simple Pie Chart
expenses <- c(600, 300, 150, 100, 200)
categories <- c("Housing", "Food", "Clothing", "Entertainment", "Other")
pie(expenses, labels = categories, main = "Monthly Expenses Breakdown",
col = c("red","orange","yellow","blue","green"),
border = "brown", clockwise = TRUE)
3.9.3 Pie Chart with Slice Percentages
pie_percent <- round(100 * expenses / sum(expenses), 1)
pie_labels <- paste(pie_percent, "%", sep = "")
pie(expenses, labels = pie_labels, main = "Monthly Expenses Breakdown",
col = rainbow(5), border = "white")
legend("topright", legend = categories, fill = rainbow(5))
3.9.4 3D Pie Charts
library(plotrix)
pie3D(expenses, labels = pie_labels, explode = 0.1,
main = "Monthly Expenses (3D View)", col = rainbow(length(expenses)),
height = 0.2, theta = 1.0, start = 1.5, labelcex = 1.2)
legend(x = 1.5, y = 1.0, legend = categories, fill = rainbow(length(expenses)),
xpd = TRUE, cex = 0.8, bty = "n")
📘 R Programming · Unit 3 · Matrices, Arrays, Factors, Data Frames & Graphics
Prepared by ARO Study Circle
0 Comments