Introduction To R Programming
Introduction To R Programming
Hypothesis Testing
T-test (one-sample, Paired, independent)
Z-test (for large sample)
Chi-square test
F-test
ANOVA Procedure
One way ANOVA
REGRESSION MODELS
•Simple Linear Regression
•Multiple Regression Analysis
•Using categorical/dummy variables in regression
•Logistics Regression
CIA: RESEARCH PROJECT OVERVIEW
•Objective: Apply statistical concepts (Descriptive Stats, Hypothesis Testing, ANOVA,
Regression, Visualisation) using R programming on a self-selected dataset.
•Deliverables: 3-page written report (PDF), R script, and Dataset
•Evaluation (40 Marks): Research Question (5) | Methodology (5) | Findings (10)
|visualisation (5) Data Handling (5) | Code Quality (5) | Viva (5)
•Submission: Hard copy due on submission date. Front & back print, no title sheet, no
plastic files, black-and-white, stapled.
•AI & Ethics: AI tools may assist with coding or writing clarity, but all analysis must be
your own. Misuse is academic misconduct.
ASSESSMENT FORMAT
•Questions will examine both theoretical understanding and practical applications.
•The assessment criteria is mentioned below:
# Subtraction # Division
10 - 4 # Result: 6 15 / 3 # Result: 5
R AS A CALCULATOR – ADVANCED OPERATIONS
# Integer Division
17 %/% 5 # Result: 3
R AS A CALCULATOR – MATHEMATICAL FUNCTIONS
# Absolute Value
abs(-7) # Result: 7
R SYNTAX BASICS – VARIABLE ASSIGNMENT
# Using <-
x <- 10
# Using =
y = 20
# Print values
x # Display x
print(y) # Explicit print
R SYNTAX BASICS – CODE COMMENTS
# This is a single line comment
# Multiple line comments
# Use hashtag for each line
# Like this
DATA TYPES IN R
# Numeric # Logical (Boolean)
x <- 42.5 # Decimal numbers is_student <- TRUE # Note the
capitalization
y <- 42 # Integers has_car <- FALSE
Homogeneous? All same type All same type Can mix types
list(a=1,
Example c(1,2,3) matrix(1:4,2,2)
b="hi")
WHAT IS A VECTOR?
•A vector in R is like a container that holds a
sequence of elements of the same type.
•Think of it as a row of boxes, where each box must
contain the same kind of thing.
•It's one of the most fundamental data structures in R.
HOW TO CREATE A VECTOR?
Key things to remember about creation of vector
1. The use of c () function
# The c() function combines elements into a vector
# 'c' stands for 'combine' or 'concatenate’
favorite_numbers <- c(7, 13, 42, 9)
# Vector arithmetic
numbers + 2 # Adds 2 to each element
numbers * 3 # Multiplies each element by 3
numbers + numbers # Element-wise addition
Remember, the key to understanding R syntax is practice and experimentation. Don't be afraid to
use the help() function or ? operator to learn more about any function we've covered.
ASSESSMENT CLUES
Question 1: Create a vector of 5 different temperatures in Celsius
Clues:
•Remember to use the c() function
•Choose reasonable temperatures (maybe between 0°C and 30°C)
•Decimal numbers are allowed
# Answer:
temperatures_c <- c(15.5, 22.3, 18.7, 25.1, 12.8)
ASSESSMENT CLUES
Question 2: Convert these temperatures to Fahrenheit
Clues:
Formula is (C × 9/5) + 32
You can perform this operation on the entire vector at once
Remember order of operations
# Answer:
temperatures_f <- (temperatures_c * 9/5) + 32
# This creates: 59.9°F, 72.14°F, 65.66°F, 77.18°F, 55.04°F
ASSESSMENT CLUES
Question 3: Create a logical vector indicating which temperatures are above 20°C
Clues:
•Use a comparison operator (>)
•The result will be TRUE/FALSE for each element
•R will automatically compare each element to 20
# Answer:
above_20 <- temperatures_c > 20
# This creates: c(FALSE, TRUE, FALSE, TRUE, FALSE)
ASSESSMENT CLUES
Question 4: Calculate the mean temperature in Celsius
Clues:
•There's a built-in function for calculating means
•The function starts with 'm'
•No need to sum and divide manually
# Answer:
mean_celsius <- mean(temperatures_c)
# Result: 18.88°C
ASSESSMENT CLUES
Question 5: Calculate the mean temperature in Fahrenheit
Clues:
You can either:
Convert the mean Celsius to Fahrenheit
OR calculate the mean of the Fahrenheit vector
# Method 2:
mean_fahrenheit2 <- mean(temperatures_f)
# Result: 65.984°F
COMMON MISTAKES TO WATCH FOR:
[Link] parentheses in the F to C conversion
[Link] celsius_temps instead of temperatures_c (naming consistency)
[Link] c instead of C in variable names
[Link] to do calculations one temperature at a time instead of using vector
operations
REFRESH ASSESSMENT
Movies to Rate:
[Link]
[Link] Wild Robot
[Link] Story
[Link] to Train Your Dragon
[Link] Lion King
Exercise 1: Creating Rating Vector Create a vector with your ratings for these movies. Clue: Use the c() function, and
remember ratings should be between 1-10. For example: ratings <- c(9, 8.5, ...)
Exercise 2: Star Rating Conversion Convert your 10-point ratings to a 5-star scale. Clue: What mathematical operation would
convert a 10-point scale to a 5-point scale?
Exercise 3: Favorite Movies Create a logical vector showing which movies you rated above 8. Clue: Use your original ratings
vector with the > operator
Exercise 4: Average Rating Calculate your mean rating across all five movies. Clue: Use the mean() function on your ratings
vector
Bonus Challenge: Can you create a named vector that pairs each movie title with its rating? Clue: Think about using names()
or creating the vector with names from the start!
WHAT IS THE R WORKSPACE?
Think of the R workspace as your digital desk where you're doing
data analysis. Just like a physical desk:
•It's where all your "things" (objects) live while you're working
•Everything you create (variables, functions, data) stays there until
you remove it
•It's your temporary working environment
WHAT IS THE R WORKSPACE?
# Create some objects in your workspace
x <- 10
names <- c("Alice", "Bob", "Charlie")
data <- [Link](id = 1:3, score = c(85, 92, 78))
det(A)
# Dimensions
dim(A)
nrow(A)
ncol(A)
BASIC MATRIX INDEXING
Create a sample matrix
Single element
M[1, 1] # First row, first column
M <- matrix(1:12, 3, 4) M[2, 3] # Second row, third column
print(M)
# [,1] [,2] [,3] [,4] Entire row
M[1, ] # First row
# [1,] 1 4 7 10 M[2, ] # Second row
# [2,] 2 5 8 11
# [3,] 3 6 9 12 Entire column
M[, 1] # First column
M[, 2] # Second column
ADVANCED MATRIX INDEXING
Multiple rows or columns Logical indexing
M[1:2, ] # First two rows M[M > 5] # All elements greater than 5
M[, 2:3] # Second and third columns M[M %% 2 == 0] # All even numbers
M[c(1,3), ] # First and third rows
Replacing values
M[1, 1] <- 100 # Replace single element
M[1, ] <- c(1,1,1,1) # Replace entire row
M[M < 5] <- 0 # Replace all elements less than 5
NAMED INDEXING
Creating matrix with row and column names
Accessing by names
students <- c("Alice", "Bob", "Charlie")
grades["Alice", "Math"]
subjects <- c("Math", "Physics",
"Chemistry", "Biology") grades["Bob", ]
grades <- matrix(c(85,92,78,88, grades[, "Physics"]
90,85,92,95,
78,80,85,82),
nrow=3, ncol=4,
dimnames=list(students, subjects))
IN-CLASS ASSESSMENT 1
Exercise 1: Matrix Creation
Create a 3x3 matrix containing numbers 1 to 9, filled by row.
Then: a) Extract the second row
b) Extract the third column
c) Change the diagonal elements to 0
SOLUTION TO ASSESSMENT 1
# Creating the matrix
mat <- matrix(1:9, 3, 3, byrow = TRUE)
# a) Second row
second_row <- mat[2,]
# b) Third column
third_col <- mat[,3]
# c) Changing diagonal
diag(mat) <- 0
IN CLASS- ASSESSMENT 2
Given matrices A and B:
A <- matrix(c(2, 0, -1, 1), 2, 2)
B <- matrix(c(1, 2, 3, 4), 2, 2)
Calculate:
a) A + B
b) Matrix Multiplication
c) The determinant of A
d) The inverse of B
e) Scalar Multiplication
SOLUTION TO ASSESSMENT 2
# a) Addition
sum_AB <- A + B
# b) Matrix multiplication
prod_AB <- A * B
# c) Determinant
det_A <- det(A)
# d) Inverse
inv_B <- solve(B)
IN CLASS- ASSESSMENT 3
A company tracks sales data for Tasks:
three products across four quarters:
a) Calculate the total sales for
sales_data <- matrix(c( each product
100, 120, 80, b) Find the quarter with highest
150, 130, 90, total sales
120, 140, 85, c) Calculate the percentage
180, 160, 95 change in sales from Q1 to Q4
), nrow = 4, byrow = TRUE)
for each product
SOLUTION TO ASSESSMENT 3
# a) Total sales per product
product_totals <- colSums(sales_data)
# c) Percentage change
percentage_change <- (sales_data[4,] - sales_data[1,]) / sales_data[1,] * 100
IN-CLASS ASSESSMENT 4
You are a data analyst at a school analyzing student test scores. You have the following matrix of
test scores for 5 students across 4 subjects:
1. Create the scores matrix
85, 92, 78, 95, # Student 1
72, 85, 88, 90, # Student 2
95, 88, 92, 85, # Student 3
65, 70, 75, 68, # Student 4
88, 85, 90, 92 # Student 5
2. Add names to the matrix
student_names are Emma, James, Sophia, Lucas, Olivia
subject_names are Math, Science, English, History
SOLUTION TO ASSESSMENT 4
Create the scores matrix
Add names to the matrix
scores <- matrix(c(
student_names <- c("Emma",
85, 92, 78, 95, # Student 1 "James", "Sophia", "Lucas",
"Olivia")
72, 85, 88, 90, # Student 2
95, 88, 92, 85, # Student 3 subject_names <- c("Math",
"Science", "English", "History")
65, 70, 75, 68, # Student 4
rownames(scores) <- student_names
88, 85, 90, 92 # Student 5
colnames(scores) <- subject_names
), nrow = 5, byrow = TRUE)
IN-CLASS ASSESSMENT 4
Complete these tasks:
a) Extract Sophia's scores for all subjects
b) Find all test scores above 90
c) Extract the Science and History scores for Emma and Olivia
d) Replace all scores below 70 with NA
e) Calculate the average score for each student (use rowMeans())
f) Find which students have at least one score above 90 (use logical indexing)
SOLUTION TO ASSESSMENT 4
a) Sophia's scores
c) Science and History scores for e) Average score for each student
sophia_scores <- Emma and Olivia
student_averages <-
scores["Sophia", ] selected_scores <- rowMeans(scores, [Link] = TRUE)
scores[c("Emma", "Olivia"),
print("Sophia's scores:") c("Science", "History")] print("Student averages:")
print(selected_scores)
f) Students with at least one score
b) Scores above 90 above 90
d) Replace scores below 70 with students_high_scores <-
high_scores <- NA unique(rownames(scores)[apply(s
scores[scores > 90] cores > 90, 1, any, [Link] =
scores[scores < 70] <- NA TRUE)])
print("Scores above 90:") print("Scores with NA:") print("Students with scores above
90:")
print(high_scores) print(scores)
print(students_high_scores)
WHAT ARE LISTS?
Lists in R are recursive data structures that act as containers capable of storing
elements of different types and lengths. They are essentially "containers of
containers" that can hold any type of R object, including other lists. Think of a list as a
versatile box that can contain smaller boxes of different sizes and contents.
Key characteristics of lists:
•Can store elements of different types
•Elements can have different lengths
•Can be named or unnamed
•Can be nested (lists within lists)
•Are recursive (can contain themselves)
DIFFERENCE BETWEEN SIMPLE LIST AND NESTED
LIST
Feature Simple List Nested List
Can mix data types (numeric, character, logical, Can contain lists, lists inside lists, matrices, data
Element types
vector). frames, functions, etc.
Ease of manipulation Easy to modify or extract. Requires more careful indexing to avoid errors.
Memory & complexity Simpler, lighter. Can become complex based on depth of nesting.
Removing elements
my_list$new_element <- NULL
LIST FUNCTIONS
Length of list Unlist (flatten) a list
length(my_list) unlist(my_list)
c) All projects
e) Update IT budget
all_projects <-
unlist(lapply(company$departments, company$departments$IT$budget <- 120000
function(x) x$projects))
EXERCICE 3: LIST MANIPULATION CHALLENGE
Tasks: a) Calculate weighted average for each class b) Find the class with highest average c) Add a "passing_rate"
element to each class (percentage of scores ≥ 85) d) Create a summary list with statistics for each class
c) Add passing rates
exam_data <- lapply(exam_data, function(class) {
SOLUTION TO EXERCISE 3 class$passing_rate <- mean(class$scores >= 85) * 100
return(class)
a) Calculate weighted averages
})
weighted_averages <-
lapply(exam_data, function(class) {
d) Create summary
sum(class$scores * class$weights)
summary <- lapply(exam_data, function(class) {
})
list(
mean = mean(class$scores),
b) Highest average class
sd = sd(class$scores),
highest_class <-
names(exam_data)[[Link](unlist( passing_rate = class$passing_rate,
weighted_averages))] weighted_avg = sum(class$scores * class$weights)
)
})