0% found this document useful (0 votes)
4 views83 pages

Introduction To R Programming

The document outlines a syllabus for a course on Data Analytics with R, covering topics such as R programming basics, exploratory data analysis, statistical tests, and regression models. It includes details on a research project, assessment format, and practical exercises to reinforce learning. The document also emphasizes the importance of the R workspace for organization, memory management, and reproducibility.

Uploaded by

chhavs2812
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views83 pages

Introduction To R Programming

The document outlines a syllabus for a course on Data Analytics with R, covering topics such as R programming basics, exploratory data analysis, statistical tests, and regression models. It includes details on a research project, assessment format, and practical exercises to reinforce learning. The document also emphasizes the importance of the R workspace for organization, memory management, and reproducibility.

Uploaded by

chhavs2812
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Anuhya Korrapati

INTRODUCTION TO R PROGRAMMING Senior Research Fellow


Department of Economics
SYLLABUS - DATA ANALYTICS WITH R.
The course content is structured into several major sections with specific time
allocations:
1. R Programming Introduction
2. Exploratory Data Analysis
3. Major Statistical Tests
4. Regression Models
R PROGRAMMING INTRODUCTION
•Using R as a calculator
•The basics of R syntax
•The R workspace
•Types of variables in R: numbers, character, logical, and factors
•Vectors and handling vectors (vector operations)
•Matrices and matrix operations
•Lists and list operations
EXPLORATORY DATA ANALYSIS
Data Frames and First Steps in Graphics
•Creating data frames using keyboard and reading
CSV files
Data Manipulation: Control structures in R
•Data frame operations
•Slicing and dicing data frames
•Control Structures in R
•Installing packages in R •Functions in R
•Basic plotting in R •User defined functions in R
•Some numeric and character functions
in R
MAJOR STATISTICAL TESTS
Descriptive Statistics
Central tendency – Mean, Median, Mode, Weighted Averages
Dispersion – Range, Variance and Standard Deviation
Cross-Tabulations
Correlation – Pearsons and Spearmans

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:

Theoretical component Practical implementation


Understanding of statistical concepts Clear and organised code with #comments
Rationale for model/test selection Accurate implementation of the code
Model/test process Following appropriate naming conventions
Valid interpretation of R output/results Appropriate test/model selection with correct model specification
WHAT IS R?

•Free, open-source programming language


•Designed for statistical computing and graphics
•Large community and extensive package ecosystem
•Industry standard for data analysis
RSTUDIO INTERFACE
R AS A CALCULATOR – BASIC ARITHMETIC OPERATIONS
# Addition # Multiplication
5 + 3 # Result: 8 6 * 7 # Result: 42

# Subtraction # Division
10 - 4 # Result: 6 15 / 3 # Result: 5
R AS A CALCULATOR – ADVANCED OPERATIONS

# Exponents # Modulus (Remainder)


2^3 # Result: 8 17 %% 5 # Result: 2

# Integer Division
17 %/% 5 # Result: 3
R AS A CALCULATOR – MATHEMATICAL FUNCTIONS

# Square Root # Logarithms


log(10) # Natural log
sqrt(16) # Result: 4
log10(100) # Base 10 log

# 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

# Check data types using class()


# Character (strings)
function
name <- "Alice" class(x) # "numeric"
message <- 'Hello, World!' # class(name) # "character"
Both single and double quotes class(is_student) # "logical"
work
SUMMARY OF DIFFERENCES
Feature Vector Matrix List

Dimensions 1D 2D Flexible (can nest any)

Homogeneous? All same type All same type Can mix types

Access x[ ] x[row, col] x[[ ]] or $

Numeric or character Anything (models, data


Common contents Numbers, text
data frames, etc.)

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)

2. All elements must be the same type:


# R will convert all elements to the same type if you mix them
mixed <- c(1, "hello", 3) # Everything becomes character: "1" "hello" "3"
HOW TO CREATE A VECTOR?
3. Vector operations (you can perform operations on all elements at once)
# Multiply every number by 2
ages <- c(25, 30, 35)
ages * 2 # Results in: 50, 60, 70

# Add two vectors


vector1 <- c(1, 2, 3)
vector2 <- c(10, 20, 30)
vector1 + vector2 # Results in: 11, 22, 33
HOW TO CREATE A VECTOR?
3. Vector operations (you can perform operations on all elements at once)
# Multiply every number by 2
ages <- c(25, 30, 35)
ages * 2 # Results in: 50, 60, 70

# Add two vectors


vector1 <- c(1, 2, 3)
vector2 <- c(10, 20, 30)
vector1 + vector2 # Results in: 11, 22, 33
HOW TO CREATE A VECTOR?
4. Accessing elements (R uses 1-based indexing):
names <- c("Alice", "Bob", "Charlie", "David")
names[1] # Gets "Alice" (first element)
names[c(1, 3)] # Gets "Alice" and "Charlie"
names[2:4] # Gets elements from index 2 to 4
VECTOR CREATION AND BASIC OPERATIONS
# Create vectors using c() function (combine)
numbers <- c(1, 2, 3, 4, 5)
names <- c("Alice", "Bob", "Charlie")
logical_values <- c(TRUE, FALSE, TRUE)

# Vector arithmetic
numbers + 2 # Adds 2 to each element
numbers * 3 # Multiplies each element by 3
numbers + numbers # Element-wise addition

# Vector indexing (starts at 1, not 0!)


numbers[1] # First element
numbers[c(1, 3)] # First and third elements
numbers[2:4] # Elements from index 2 to 4
BASIC FUNCTIONS AND ARGUMENTS
# Function structure
mean(numbers) # Calculate average
sum(numbers) # Sum all elements
length(numbers) # Number of elements

# Functions with multiple arguments


round(3.14159, digits = 2) # Named arguments
seq(from = 1, to = 10, by = 2) # Generate sequence
ASSESSMENT
Let's practice these concepts with some exercises:
[Link] a vector of 5 different temperatures in Celsius
[Link] these temperatures to Fahrenheit using the formula (C × 9/5) + 32
[Link] a logical vector indicating which temperatures are above 20°C
[Link] the mean temperature in both Celsius and Fahrenheit

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

Both methods should give the same result


# Answer:
# Method 1:
mean_fahrenheit1 <- (mean_celsius * 9/5) + 32

# 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))

# See what's on your "desk" (workspace)


ls() # Will show: "x", "names", "data"
WHY IS THE R WORKSPACE IMPORTANT?
1. Organization

# Good practice: Start with a clean workspace


rm(list = ls()) # Clears everything

# Check if workspace is clean


ls() # Should show nothing
WHY IS THE R WORKSPACE IMPORTANT?
2. Memory Management

# See how much memory an object uses


[Link](data)

# Remove objects you no longer need


rm(x)
WHY IS THE R WORKSPACE IMPORTANT?
3. Project Reproducibility

# Save your entire workspace


[Link]("project_workspace.RData")

# Load it later or share with colleagues


load("project_workspace.RData")
WHY IS THE R WORKSPACE IMPORTANT?
4. Troubleshooting

# Check what objects exist


ls()

# Examine object structure


str(data) # Shows object's structure
R WORKSPACE PRACTICE WITH BUILT-IN DATASETS
Exercise 1: Organization
Task: Let's organize our workspace using familiar datasets.

# Step 1: Clear workspace # Step 4: Look at our data


rm(list = ls()) head(mtcars) # Look at first few rows of car data
head(iris) # Look at first few rows of iris data
# Step 2: Load basic datasets Tail(mtcars) #Look at last few rows of car data
data(mtcars) # Car data
data(iris) # Flower data Step 5: Understand the structure of each dataset
str(mtcars) # Shows structure of mtcars: variables, types, first few
# Step 3: See what's in our workspace values
ls() # Should show "mtcars" and "iris" str(iris) # Shows structure of iris: variables, types, first few values
R WORKSPACE PRACTICE WITH BUILT-IN DATASETS
Exercise 2: Memory Management
Task: Understand how much space different datasets occupy.
# Step 1: Clear workspace and load datasets # Step 4: Look at structure of each dataset
rm(list = ls()) str(mtcars)
data(mtcars) str(iris)
data(iris) str(airquality)
data(airquality)
# Step 5: Remove largest dataset
# Step 2: Check what's in workspace rm(airquality)
ls()
# Step 6: Verify removal
# Step 3: Look at size of each dataset ls()
[Link](mtcars)
[Link](iris)
[Link](airquality)
R WORKSPACE PRACTICE WITH BUILT-IN DATASETS
Exercise 3: Saving and Loading Workspace
Task: Practice saving and loading different datasets.
# Step 4: Save entire workspace
# Step 1: Start fresh
[Link]("my_datasets.RData")
rm(list = ls())
save(mtcars, file = "just_cars.RData") #Save Specific Object
# Step 2: Load specific datasets
# Step 5: Clear workspace
data(mtcars)
rm(list = ls())
data(iris)
ls() # Should show nothing
# Step 3: Look at their structure
# Step 6: Load saved workspace
str(mtcars)
load("my_datasets.RData")
str(iris)
# Step 7: Verify structures are same as before
str(mtcars)
str(iris)
R WORKSPACE PRACTICE WITH BUILT-IN DATASETS
Exercise 4: Troubleshooting Dataset Issues
Task: Identify and understand common dataset issues
# Step 1: Start fresh and load datasets # Step 4: Count missing values in airquality
rm(list = ls()) sum([Link](airquality)) # Total NAs
data(airquality) colSums([Link](airquality)) # NAs by column
data(mtcars)
# Step 5: Check data types
# Step 2: Look at complete structure class(airquality)
str(airquality) class(mtcars)
str(mtcars)

# Step 3: Check for missing values


summary(airquality)
summary(mtcars) # Will show NAs if present
R – WORKSPACE WORKING DIRECTORY
# See current location
getwd()

# List what's in this location


[Link]()

# Change location (use forward slashes!)


setwd("C:/Users/Documents/path…") # Windows
setwd("/Users/Documents/path…") # Mac/Linux
R – WORKSPACE HISTORY MANAGEMENT
# View recent commands
history()

# Save command history


savehistory("my_commands.Rhistory")

# Load previous history


loadhistory("my_commands.Rhistory")
CHECKING DATA TYPES
# Using class() function # Using [Link]() functions
class(Datasetname$age) # "numeric" [Link](Datasetname$age) # TRUE
class(Datasetname$name) # "character" [Link](Datasetname$name) # TRUE
class(Datasetname$is_student) # "logical" [Link](Datasetname$has_passed) # TRUE
class(Datasetname$education) # "factor" [Link](Datasetname$education) # TRUE
R WORKSPACE PRACTICE WITH AIR QUALITY DATA
Task: Organization # Step 1: Clear workspace
rm(list = ls()) # Removes all objects
Let's organize our workspace
using the airquality dataset. # Step 2: Load dataset
data(airquality) # Built-in dataset

# Step 3: See what's in workspace


ls() # Should show "airquality"

# Step 4: Look at data structure


head(airquality) #First few rows
tail(airquality) #Last few rows
str(airquality) # Structure of dataset
R WORKSPACE PRACTICE WITH AIR QUALITY DATA
# Step 1: Clear and load data
rm(list = ls())
Task: Memory data(airquality)
Management
# Step 2: Check original size
Understand how much [Link](airquality)
space different data
objects occupy. # Step 3: Create subsets and compare sizes – Summer and Spring
summer_data <- airquality[airquality$Month >= 6 & airquality$Month
<= 8, ]
airquality[airquality$Month == 5, ]
[Link](summer_data)
[Link](spring_data)

# Step 4: Remove largest object


rm(summer_data) # Free up memory
ls() # Check what remains
R WORKSPACE PRACTICE WITH AIR QUALITY DATA
# Step 1: Start fresh
rm(list = ls())
Task: Saving and data(airquality)
Loading # Step 2: Create objects to save
Practice saving and hot_days <- airquality[airquality$Temp > 85, ]
loading workspace windy_days <- airquality[airquality$Wind > 10,]
objects. # Step 3: Save multiple ways
save(hot_days, file = "hot_days.RData") #Save single object
save(windy_days, file = "weather_data.RData") #Save multiple
[Link]("full_workspace.RData") #Save everything

# Step 4: Clear workspace


rm(list = ls())
ls()

# Step 5: Load data back


load("hot_days.RData") # Loads specific file
ls() # Clue: Check what was loaded
R WORKSPACE PRACTICE WITH AIR QUALITY DATA
# Step 1: Load data and check issues
rm(list = ls())
Task:Troubleshooting data(airquality)

Identify and fix # Step 2: Look for missing values


common dataset issues. sum([Link](airquality)) # Total missing values
colSums([Link](airquality)) # Missing by column

# Step 3: Check data types


sapply(airquality, class) #What type is each column?

# Step 4: Look for unusual values


summary(airquality) # Find min/max/unusual values

# Step 5: Fix common issues


clean_data <- [Link](airquality) # Remove incomplete rows
nrow(airquality) - nrow(clean_data) # How many rows remain?
R WORKSPACE PRACTICE WITH AIR QUALITY DATA
# Step 1: Check location
Task:Directory getwd() #Where are we?
Management
# Step 2: Create project directory
Manage working [Link]("airquality_project") # Make new folder
directories and files.
# Step 3: Change directory
setwd("airquality_project") # Move to new folder

# Step 4: List files


[Link]() # What's in this directory?

# Step 5: Save and verify


save(airquality, file = "raw_data.RData")
[Link]() # Should see new file
WHAT IS A MATRIX?
A matrix is a two-dimensional array of numbers arranged in rows and columns. In
mathematics and statistics, matrices are crucial for:
•Solving systems of linear equations
•Data transformation
•Statistical analysis
•Image processing
•Network analysis
CREATING MATRICES IN R
Basic syntax Filling by row
matrix(data, nrow, ncol, byrow = FALSE) mat2 <- matrix(c(1, 2, 3, 4, 5, 6),
nrow = 2, ncol = 3, byrow =
TRUE)
Creating a 2x3 matrix
print(mat2)
mat1 <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3)
# Output:
print(mat1)
# Output: # [,1] [,2] [,3]
# [,1] [,2] [,3] # [1,] 1 2 3
# [1,] 1 3 5 # [2,] 4 5 6
# [2,] 2 4 6
USING RBIND() AND CBIND()
Creating matrices by binding vectors
row1 <- c(1, 2, 3)
row2 <- c(4, 5, 6)
mat3 <- rbind(row1, row2) # Binding by rows
mat4 <- cbind(c(1, 4), c(2, 5), c(3, 6)) # Binding by columns
BASIC MATRIX OPERATIONS
Addition and subtraction Scalar multiplication
A <- matrix(c(1, 2, 3, 4), 2, 2) scalar_mult <- 2 * A
B <- matrix(c(5, 6, 7, 8), 2, 2)
sum_matrix <- A + B Matrix multiplication
diff_matrix <- A - B product_matrix <- A * B
IMPORTANT MATRIX FUNCTIONS
# Inverse
# Transpose
solve(A)
t(A)
# Diagonal elements
# Determinant diag(A)

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)

# b) Quarter with highest sales


quarter_totals <- rowSums(sales_data)
max_quarter <- [Link](quarter_totals)

# 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(sophia_scores) print("Selected scores:") 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

A list where one or more elements are themselves lists


Definition A list where all elements are at the same level.
(multi-level structure).

Structure Flat (one-dimensional). Hierarchical (multi-layered).

Can mix data types (numeric, character, logical, Can contain lists, lists inside lists, matrices, data
Element types
vector). frames, functions, etc.

More complex because you may need multiple [[


Accessing elements Straightforward using [ ], [[ ]], or $.
]] levels (e.g., nested_list$b$x).

Representing structured, grouped, or hierarchical


Common use Storing small, simple collections of different types.
information.

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.

Example list(1, "hi", TRUE) list(a = 1, b = list(x = 2, y = 3))


CREATING LISTS IN R
Basic list creation Nested lists (a nested list is a
simple_list <- list(1, "hello", TRUE) list within another list, creating
different levels of hierarchy.)
Named list elements nested_list <- list(
student <- list( a = 1:3,
name = "John",
b = list(x = 1, y = 2),
age = 20,
grades = c(85, 92, 78), c = matrix(1:4, 2, 2)
active = TRUE )
)
LIST INDEXING AND SUBSETTING
Single Bracket [ ] - Returns a List

# Create a sample list


my_list <- list(a = 1:3, b = "hello", c = TRUE)

# Single bracket returns a list


sub_list <- my_list[1] # Returns list with first element
sub_list <- my_list["a"] # Returns list with element named "a"
LIST INDEXING AND SUBSETTING
Double Bracket [[ ]] - Returns the Element
Double bracket returns the actual element
element <- my_list[[1]] # Returns 1:3
element <- my_list[["a"]] # Returns 1:3

Dollar Sign $ - Named Access


Dollar sign for named elements
value <- my_list$a # Returns 1:3
LIST OPERATIONS
Adding new elements
my_list$new_element <- "new"

Removing elements
my_list$new_element <- NULL
LIST FUNCTIONS
Length of list Unlist (flatten) a list
length(my_list) unlist(my_list)

Names of list elements Combine lists


names(my_list) list1 <- list(a = 1, b = 2)
list2 <- list(c = 3, d = 4)
combined <- c(list1, list2)
LIST MANIPULATION
Modify multiple elements
my_list[c("a", "b")] <- list(1:5, "world")

Apply function to list elements


lapply(my_list, class) # Returns classes of elements
sapply(my_list, length) # Simplified return

Filter list elements


filtered <- my_list[sapply(my_list, [Link])]
REAL-WORLD EXAMPLE: STUDENT RECORDS
EXERCISE 1: LIST CREATION AND ACCESS
Create a list representing a book with the following information:
• title (string)
• author (string)
• year (numeric)
• genres (vector of strings)
• ratings (vector of numbers 1-5)

Then: a) Extract the author name using [[]]


b) Extract the genres using $
c) Calculate the average rating
d) Add a new element "in_print" = TRUE
e) Remove the year element
SOLUTION TO EXERCISE 1
c) Average rating
Create book list
a) Extract author avg_rating <- mean(book$ratings)
book <- list(
author <- book[["author"]]
title = "Data Science Basics",
d) Add in_print
author = "Jane Doe",
b) Extract genres book$in_print <- TRUE
year = 2023,
genres <- book$genres
genres = c("Technology",
"Education", "Reference"), e) Remove year
ratings = c(4, 5, 3, 5, 4, 5) book$year <- NULL
)
EXERCISE 2: NESTED LIST OPERATIONS
Complete these tasks: a) Extract all IT employees b) Calculate total budget across departments c) Create a
vector of all projects d) Add a new department "Finance" e) Update IT budget to 120000
SOLUTION TO EXERCISE 2
a) IT employees d) Add Finance department
it_employees <- company$departments$Finance <- list(
company$departments$IT$employees
employees = c("Eve"),
b) Total budget budget = 75000,
total_budget <- projects = c("Budgeting")
sum(sapply(company$departments,
function(x) x$budget)) )

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)
)
})

You might also like