Data Science Notes
Data Science Notes
Key Components:
- Data Collection
- Data Cleaning
- Exploratory Data Analysis (EDA)
- Model Building
- Model Evaluation
- Deployment
1. Explosion of Data
Traditional methods can’t handle this volume — data science makes sense of it.
2. Better Decision-Making
3. Automation of Tasks
Chatbots, fraud detection, and recommendation engines run without human input.
4. Personalization
Weather apps, stock market tools, and healthcare systems use data science to
predict future events.
Real-Life Examples
Traditional tools like Excel and SQL fail when dealing with large, complex, or real-time
data. Data Science enables better decision-making, predictive analysis, automation, and
personalization.
Example: Spotify uses data science to generate personalized playlists by analyzing user
listening patterns.
Vectors
Matrices
Linear transformations
In data science, data is often represented in matrix or vector form (think of an Excel
spreadsheet — rows and columns = matrices!).
Linear Algebra in Data Science:
A. Vectors
A vector is just an ordered list of numbers (1D array). It can represent features of data.
Here, each value is a feature (Math, English, Science). This vector represents one student.
Operations:
Addition: [1,2]+[3,4]=[4,6]
B. Matrices
A matrix is a 2D array — rows and columns of numbers. In data science, datasets are
typically matrices.
Operations:
Matrix multiplication
Transpose
Inverse
C. Linear Equations
A linear equation is a rule that tells you how two or more quantities (variables) are
related, and when you draw it on a graph, it forms a straight line.
Total=10x
A 2-Variable Example
20x+10y=100
This equation tells you all combinations of apples and mangoes that cost ₹100.
2x+3y=8 x−y=2
A⋅X=B
Where:
Matrix A = coefficients
Vector X = variables
1. Substitution Method
From x−y=2
x=y+2
Substitute into the first equation:
2(y+2)+3y=8
⇒2y+4+3y=8
⇒5y=4
⇒y=0.82
Then:
x=0.8+2=2.8
2. Elimination Method
We want to eliminate one of the variables by making their coefficients the same in both
equations. Let's eliminate x by aligning coefficients.
We already have:
Multiply Equation (1) by 2 so that the coefficient of xxx becomes 2 in both equations:
(2x+3y)−(2x−2y)=8−4
2x+3y−2x+2y=4
⇒5y=4
⇒y=0.8
x−y=2x
Substitute y=0.8
x−0.8=2
⇒x=2.8
x=2.8, y=0.8x
3. Matrix Method (Using Inverse)
1) 2x + 3y = 8
2) x - y = 2
Matrix Representation:
Where:
Matrix Equation:
Python Code:
import numpy as np
B = [Link]([8, 2])
X = [Link](A, B)
print(X)
Explanation:
We are using NumPy's '[Link]()' function which efficiently solves the linear system.
This method is preferred over directly calculating A⁻¹ because it's numerically stable.
Example:
2x+3y=8 and x−y=2
In matrix form:
Gaussian elimination
Matrix inverse
Python: [Link](A, b)
Problem:
A company wants to predict the salary of a person based on their years of experience.
They observe:
Salary=5000⋅Years+30000
y=mx+c
Where:
y = salary (output)
Salary=5000⋅4+30000=20000+30000=₹50,000
Answer: ₹50,000
Formula (2D):
Distance = sqrt((x2 - x1)^2 + (y2 - y1)^2)
Example:
Points A = (2, 3), B = (5, 7)
Distance = sqrt((5-2)^2 + (7-3)^2) = sqrt(9 + 16) = 5
Example:
You want to predict whether a patient has diabetes based on attributes like age, BMI, and
glucose level.
Suppose a new patient has:
- Age = 45, BMI = 28, Glucose = 140
You compare this with known patients using Euclidean distance:
Distance = sqrt((Age1 − 45)^2 + (BMI1 − 28)^2 + (Glucose1 − 140)^2)
The K-NN algorithm finds the K closest patients and takes a majority vote (for
classification) or average value (for regression).
2. K-Means Clustering
Example:
A retail company wants to segment its customers based on:
- Annual income
- Spending score
Each customer is a point in 2D space (e.g., Income = ₹5L, Score = 60).
The algorithm assigns customers to nearest cluster centers using Euclidean distance,
updates centers, and repeats.
3. Outlier Detection
4. Recommender Systems
Example:
Netflix recommends movies based on user ratings.
User A = [4, 5, 3, 1], User B = [5, 5, 2, 1]
Euclidean distance = sqrt((4-5)^2 + (5-5)^2 + (3-2)^2 + (1-1)^2) = sqrt(2)
Smaller distance = more similar tastes → Recommend User B's liked movies to User A.
Purpose: Match new images to known images (like face unlock in phones).
Example:
Each image is represented as a high-dimensional vector of pixel values.
Euclidean distance is used to find the closest stored image to the new one.
Minimum distance → best match.
Matrix Equation:
A*v=λ*v
Where:
- A is a square matrix
- v is the eigenvector
- λ (lambda) is the eigenvalue
- The direction of v remains unchanged after the transformation A is applied
Imagine you're pushing a rubber sheet from all sides (this is your transformation). Most
points on the sheet will move in new directions. But there are some directions (vectors)
where the point will just stretch or shrink, not rotate.
These directions are eigenvectors, and the stretch amount is the eigenvalue.
A = [[2, 0],
[0, 3]]
Purpose: Reduce the number of features (dimensionality) while preserving the most
important information in data.
Real-time Example:
You have a dataset with 100 features (like customer age, income, spending score, etc.).
➡PCA uses eigenvectors to identify the most important directions (called principal
components) where the data varies the most.
➡Eigenvalues tell us how much variance each component (direction) explains.
Use Case:
In a marketing campaign, you might reduce 100 features down to 2 or 3 for visualization
or faster machine learning, without losing much information.
Real-time Example:
These are computed from a large set of faces using eigenvectors of the face
dataset.
When you present your face, it checks how closely it matches the stored
eigenfaces.
Use Case:
Used in facial recognition systems like Apple Face ID, Facebook photo tagging, or
surveillance systems.
3. Latent Semantic Analysis (LSA) – Text Mining
Real-time Example:
You search on Google for “AI in medicine” but the article has the title "Artificial
Intelligence revolutionizes healthcare".
Eigenvectors help extract concepts hidden in the text even when the exact
keywords aren't present.
This is done through matrix decomposition techniques like SVD (Singular Value
Decomposition), which uses eigenvalues/vectors.
Use Case:
Search engines, topic modeling, recommendation systems like YouTube or Netflix.
4. Image Compression
Real-time Example:
Suppose you want to store 1000 face images using less memory:
Use eigenvectors to represent the most important patterns (edges, light areas,
shadows).
Use Case:
Used in image storage, transmission (e.g., medical images, CCTV footage), and apps like
Google Photos for optimization.
Real-time Example:
In training a neural network, sometimes the model becomes unstable (loss goes to NaN or
gradient explodes).
Eigenvalues of weight matrices or the Hessian matrix can tell you whether the
model is learning efficiently or diverging.
If eigenvalues are too large or negative, adjustments are made (like learning rate
tuning).
Use Case:
Used in designing optimizers, debugging training issues in TensorFlow or PyTorch.
UNIT-II
Descriptive Statistics:
Descriptive statistics summarize and organize features of a dataset using numbers, charts, and
graphs.
Examples:
Mean (Average):
Example:
Dataset = [10, 20, 30, 40]
Mean = (10+20+30+40)/4 = 25
Median:
Mode:
These values show how spread out or scattered the data is.
Range:
Formula:
Range=Maximum−Minimum
Example:
Dataset = [10, 20, 30, 40]
Range = 40 - 10 = 30
Variance:
Standard Deviation:
Let’s say you’re analyzing daily sales (in ₹) for a store over one week:
Summary Table
Data Preparation:
Data Preparation is the essential step in the data science workflow that comes before
analysis or modeling. Raw data is often incomplete, inconsistent, or messy, and cannot be
used directly for insights or machine learning.
Goal:
Transform raw data into a clean, structured, and machine-readable format.
Real-world datasets often have missing entries, like blank cells or NaN.
Techniques:
Example:
2. Removing Duplicates
Duplicate entries can skew analysis or lead to data leakage in machine learning models.
Example:
Name Email
John john@[Link]
John john@[Link]
Ensure each column has the correct type: integers, floats, strings, dates, etc.
Example:
4. Normalization or Standardization
When features (columns) have different scales, we need to scale them so that no single
feature dominates.
Normalization:
Standardization:
z = (x - mean) / std
Example:
Example:
→ Label Encoding:
Male = 1, Female = 0
→ [1, 0, 0, 1]
Let’s say you're building a churn prediction model for a telecom company. You receive the
following raw data:
Result: Clean, ready-to-use data for training your model to predict churn accurately.
Summary Table
Exploratory Data Analysis (EDA) is a crucial step in data science and analytics. It's a process
of visually and statistically summarizing the main characteristics of a dataset to uncover
patterns, find anomalies, and guide further analysis.
Types of EDA
1. Univariate Analysis
Goal: Describe the data and find patterns within a single feature.
Techniques:
o Histograms: Show the distribution of a numerical variable.
o Box Plots: Visualize the spread and detect outliers.
o Bar Charts: Used for categorical data to show frequencies.
o Summary Statistics: Measures like mean, median, mode, and standard
deviation describe central tendency and spread.
2. Bivariate Analysis
3. Multivariate Analysis
1. Understand the Problem and the Data: Before you start, you need to have a clear
understanding of the business or research question you are trying to solve. You should
also familiarize yourself with the dataset's variables, data types, and any potential
limitations.
2. Import and Inspect the Data: Load the data into your analysis environment (e.g.,
Python with Pandas). Inspect its size (rows and columns), check for missing values,
and identify data types for each variable.
3. Handle Missing Data: Decide how to manage missing values. You can either remove
the data points or impute (fill in) the values using a suitable method like the mean or
median.
4. Explore Data Characteristics: Calculate summary statistics (mean, median, standard
deviation, etc.) for numerical variables and create frequency tables for categorical
variables. This provides a clear overview of your data's properties.
5. Visualize Data Relationships: Use plots like histograms, box plots, scatter plots, and
correlation matrices to visually explore the data. This is where you'll find most of the
patterns and insights.
6. Handle Outliers: Identify and manage outliers, which are data points that are
significantly different from the rest. Outliers can be detected using methods like the
Interquartile Range (IQR) or Z-scores. You can then decide whether to remove,
adjust, or keep them, depending on the context.
7. Perform Data Transformation: If necessary, transform your data to prepare it for
modeling. This could involve scaling numerical variables, encoding categorical
variables, or applying mathematical functions to fix skewness.
8. Communicate Findings and Insights: The final step is to summarize and present
your discoveries in a clear and compelling way. Use visualizations to support your
findings and highlight key insights, limitations, and suggestions for the next steps.
Data Summarization:
Data summarization is the process of condensing large and complex datasets into smaller,
more meaningful pieces of information without losing the essence of the data. It’s like
reading the highlights of a long book instead of reading every page.
- Mean (average)
- Variance
- Standard Deviation
3. Shape of Data:
- Skewness (asymmetry)
- Kurtosis (peakedness)
Example:
Dataset: [10, 20, 30, 40, 50]
- Mean = 30
- Median = 30
- Range = 50 – 10 = 40
B. Categorical Summarization
C. Graphical Summarization
4. Example
Raw Dataset:
1 25 East 2000
2 45 West 3000
3 35 East 1500
4 28 North 4000
Summarized Data:
- Numerical Summary: Mean Age = 33.25, Mean Purchase = ₹2,625, Max Purchase = ₹4,000
Data Distribution :
Data distribution refers to the way values in a dataset are spread or arranged across possible values.
It describes the frequency or probability of occurrence of each value (or range of values) and is
fundamental in understanding data characteristics.
A. Based on Shape
2. Uniform Distribution
- Equal probability for all values in the range.
- Example: Rolling a fair die.
3. Skewed Distribution
- Positively Skewed (Right Skew): Long tail on the right; mean > median.
- Negatively Skewed (Left Skew): Long tail on the left; mean < median.
Example
Exam Scores Data:
- Mean = 72, Median = 74
- Slightly left-skewed (negative skew) → Most students scored high, but a few low scores reduced
the mean.
Summary Table
Distribution Type Shape Example Applications
Normal Symmetrical bell Human height Parametric tests,
curve regression
Uniform Flat, equal Dice rolls Random sampling
probability
Positive Skew Long tail right Income levels Wealth distribution
analysis
Negative Skew Long tail left Age at retirement Demographic studies
Bimodal Two peaks Test scores from two Population
batches segmentation
Poisson Skewed, discrete Number of Event counting
emails/day
Exponential Continuous, skewed Time to service Reliability analysis
completion
Measuring Asymmetry
In data science, asymmetry (or skewness) refers to the degree to which the distribution of
data deviates from perfect symmetry around its central value (mean or median). A symmetric
distribution has equal spread on both sides, while an asymmetric distribution shows more
concentration of values on one side.
Types of Asymmetry
Measures of Asymmetry
Formula:
Skewness = [ Σ(xi - x̄)³ ] / [ n * s³ ]
Where:
• xi = individual data values
• x̄ = mean of data
• s = standard deviation
• n = number of observations
Formula:
Skewness = ( Q3 + Q1 – 2Q2 ) / ( Q3 – Q1 )
Where:
• Q1 = First Quartile
• Q2 = Median
• Q3 = Third Quartile
0 Perfectly symmetric
Detecting Asymmetry
Example
Dataset: Exam scores = {45, 50, 52, 53, 55, 60, 95}
• Mean = 58.57
• Median = 53
• Skewness (calculated) ≈ 1.40 → Positive Skew.
The sample mean is the arithmetic average of values from a sample, not the entire population.
Formula:
x̄ = Σ(xi) / n
Where:
• x̄ = sample mean
• xi = each value in the sample
• n = number of observations in the sample
Properties
Example
Estimated Mean
The estimated mean refers to the value obtained by using the sample mean to approximate the
unknown population mean (μ).
Since we cannot compute the exact population mean without having all data points, we
estimate it using the sample mean:
μ̂ ≈ x̄
Where:
• μ̂ = estimated population mean
• x̄ = sample mean
Relationship
Estimated mean:
μ̂ ≈ 5,200
This is our best guess for the true population mean.
Symbol x̄ μ̂
Variance
Variance is a measure of the dispersion of a set of values. It calculates the average of the
squared differences between each value and the mean.
A high variance indicates that the data points are spread out widely from the mean, while a
low variance means they are closer to the mean.
Example:
Formula: z = (x - μ) / σ
Example:
If a student scored 85 on a test where the mean score was 75 and the standard deviation was
5:
z = (85 - 75) / 5 = 2
Interpretation: The student scored 2 standard deviations above the mean.
1. Variance is used in statistical modeling to understand variability and detect features with
high or low variability.
2. Z-scores are used in anomaly detection, standardizing data for machine learning models,
and in hypothesis testing.
Example: If you flip a fair coin many times, the probability of heads = 0.5 means that
in the long run, 50% of flips will show heads.
Key Idea:
Example:
Using their heights, you estimate the average for the whole college.
Applications:
Variability of Estimates:
When we take different random samples from the same population, the estimates (like sample
mean, variance, or proportion) will not be exactly the same. This variation is called
sampling variability or variability of estimates.
Example:
Imagine you want to estimate the average mark of students in a class of 500.
Applications:
Instead of just giving a single estimate (like a sample mean), CI provides a range.
Example:
Suppose a sample of 100 students has an average height = 160 cm, with a 95% confidence
interval of [158 cm, 162 cm].
This means we are 95% confident that the true average height of all students lies
between 158 and 162 cm.
If the claimed value (160) lies inside the confidence interval, we do not reject H₀.
If it lies outside the interval, we reject H₀.
Applications:
Estimating whether a factory machine produces items within acceptable size limits.
Using p-values
Definition:
The p-value is the probability of observing results as extreme as (or more extreme than) the
actual sample result, if the null hypothesis is true.
A large p-value (> 0.05) → Weak evidence against H₀ → Do not reject H₀.
Example:
Suppose you test whether a coin is fair.
Since 0.01 < 0.05, the result is very unlikely under H₀ → You reject H₀ and conclude the coin
is probably biased.
Applications:
Testing whether a new machine produces better results than the old one.
Stores values as levels (e.g., Common Classes in R Objects are given a class
Male/Female, Pass/Fail). attribute.
Numeric – Represents
Created using factor() numbers (integers or Example:
function. decimals).
person <- list(name="John",
Example: a <- 23.5 age=25)
class(a) # numeric
gender <- factor(c("Male", "Female", class(person) <- "Student"
"Male", "Female"))
Integer – Whole numbers.
print(person)
print(gender)
b <- 10L
(b) S4 Classes
Checking Object Type
class(b) # integer
Functions used: More formal with explicit
definitions.
Character – Text or string
typeof(object) → data type values.
of object. Example:
c <- "Hello"
class(object) → object setClass("Student",
class. class(c) # character
slots =
length(object) → number of Logical – Boolean values list(name="character",
elements. (TRUE or FALSE). age="numeric"))
str(object) → structure of
d <- TRUE s <- new("Student",
object. name="Alice", age=22)
class(s) # "Student" Used to execute statements based on "c" = "Third")
conditions.
(c) Reference Classes (R5) print(result)
(a) if Statement
Also known as RC classes,
used for mutable objects. Executes a block if the condition is
true. 2. Looping Structures (Iteration)
Example: x <- 10 Used for repeating a block of code
multiple times.
Person <- if(x > 5){
setRefClass("Person", (a) for Loop
print("x is greater than 5")
fields = Executes a block for each element in a
list(name="character", } sequence.
age="numeric"))
(b) if-else Statement for(i in 1:5){
p1 <-
Person$new(name="John", Executes one block if condition is print(i)
age=30) true, another if false.
}
x <- 3
p1$age # Access field
(b) while Loop
if(x > 5){
Importance of Classes
Executes as long as the condition is
print("x is greater than 5") true.
Helps in data
organization. } else { x <- 1
Enables polymorphism print("x is less than or equal to 5") while(x <= 5){
(same function behaves
differently for different } print(x)
classes).
(c) if-else ladder x <- x + 1
Forms the basis for custom
objects in advanced R Multiple conditions can be checked. }
programming.
x <- 0 (c) repeat Loop
Classes in R define the type and if(x > 0){ Executes repeatedly until a break
behavior of objects. Apart from built- condition is encountered.
in classes (numeric, integer, character, print("Positive")
etc.), R also supports object-oriented x <- 1
programming systems (S3, S4, and } else if(x < 0){
Reference Classes) that allow repeat {
creating user-defined structures. print("Negative")
print(x)
} else {
x <- x + 1
R-Programming Structures print("Zero")
if(x > 5){
Programming structures in R are the }
control mechanisms that determine break
how instructions are executed. (d) switch Statement
They help in decision-making, }
iteration, and code organization, Chooses one case among many.
making programs more flexible and }
efficient. x <- "b"
3. Control Statements
Types of Structures in R result <- switch(x,
Used to alter the flow inside loops.
1. Conditional Structures (Decision- "a" = "First",
Making) break → Terminates the loop.
"b" = "Second",
for(i in 1:10){
if(i == 5) break Arithmetic operators are used for Op Me Ex
basic mathematical Res
era ani am
print(i) calculations. ult
tor ng ple
} O
Ex Les
O u FA
a s 5<
next → Skips the current pe Descri t < LS
m tha 3
iteration. rat ption p E
pl n
or u
for(i in 1:5){ e
t
Eq 5
TR
if(i == 3) next == ual ==
10 UE
Additi 1 to 5
+ +
print(i) on 5
5
No
} t 5
Subtra 10 TR
- 5 != equ !=
ction -5 UE
4. Functions (User-Defined al 3
Structures) to
Multip 10
5
Functions group a set of instructions * licatio * c(T
0
for reuse. n 5 RU
E,
add <- function(a, b){ Divisi 10 Ele FA
/ 2 (T
on /5 me LS
return(a + b) RU
nt- E)
E,
Modul 10 & wis &
} FA
% o % e c(T
1 LS
% (remai % AN RU
print(add(5, 3)) E)
nder) 3 D E,
TR
Importance of Programming UE
Structures Power )
^ 2
(expo
or ^ 8
Helps in decision-making. **
nentiat
3 `c(
ion) Ele
TR
Reduces repetition of code
me
UE
through loops. These operations also work on vectors nt-
` ` ,
element-wise. wis
FA
e
Makes programs organized
a <- c(2, 4, 6) OR
LS
and efficient. E)
b <- c(1, 2, 3)
Enables modularity via
NO
!T FA
functions. a + b # (3, 6, 9) ! RU LS
T
E E
R-Programming structures a * b # (2, 8, 18)
include conditional statements, Used in filtering data,
looping constructs, control Logical Operations conditional checks, and
statements, and functions. They comparisons.
provide mechanisms to control Logical operators return TRUE
the flow of execution and make or FALSE values depending on Matrix Operations
R programs more structured and conditions.
powerful. Matrices in R support special
Op Me Ex operations useful in data science
Operations in R Res and linear algebra.
era ani am
ult
tor ng ple
In R, operations can be Matrix Multiplication (%*%)
performed on numbers, vectors,
matrices, and logical values. Gr A <- matrix(c(1,2,3,4), nrow=2)
They are broadly divided into eat
5> TR
Arithmetic, Logical, and > er B <- matrix(c(5,6,7,8), nrow=2)
3 UE
Matrix operations. tha
n A %*% B
Arithmetic Operations
→ Performs matrix We use the function [Link]() to Function Description
multiplication (not element- create a data frame.
wise).
str(df) Structure of data frame
# Example: Creating a data frame
Transpose of a Matrix (t())
students <- [Link]( Summary statistics of
summary(df)
A <- matrix(c(1,2,3,4), nrow=2) columns
ID = c(1, 2, 3, 4),
t(A) nrow(df) Number of rows
Name = c("Alice", "Bob", "Charlie",
→ Converts rows into columns. "David"),
ncol(df) Number of columns
Inverse of a Matrix (solve()) Age = c(20, 21, 19, 22),
colnames(df) Names of columns
A <- matrix(c(2,1,1,2), nrow=2) Marks = c(85, 90, 78, 88),
rownames(df) Names of rows
solve(A) Passed = c(TRUE, TRUE, FALSE,
TRUE) head(df) First few rows
→ Finds the inverse of matrix A
(only for square, non-singular )
matrices). tail(df) Last few rows
Applications
print(students)
Arithmetic operations → Modifying a Data Frame
Basic computations in Output:
statistics, finance, 1. Add a new column
simulations. ID Name Age Marks Passed
students$Grade <- c("A", "A+", "B",
"A")
Logical operations → Data 1 1 Alice 20 85 TRUE
filtering, condition checks,
2 2 Bob 21 90 TRUE 2. Add a new row
classification.
3 3 Charlie 19 78 FALSE new_row <- [Link](ID=5,
Matrix operations → Name="Eva", Age=20, Marks=92,
Linear regression, machine 4 4 David 22 88 TRUE Passed=TRUE, Grade="A+")
learning algorithms, image
processing. students <- rbind(students, new_row)
Accessing Data from a Data Frame
Data Frames in R 3. Remove a column
1. By column name ($)
A Data Frame in R is a two- students$Grade <- NULL
students$Name
dimensional table-like structure
where: Applications of Data Frames
# Output: "Alice" "Bob" "Charlie"
"David"
Data is stored in rows Storing datasets (CSV,
(observations) and 2. By indexing ([row, Excel, SQL tables).
columns (variables). column])
Performing data analysis,
Each column can have students[1, 2] # Row 1, Column 2 cleaning, and
different data types → "Alice" manipulation.
(numeric, character, logical,
factor). students[ , 3] # Entire 3rd column
(Age)
Input format for statistical
modeling and machine
It is similar to a learning.
spreadsheet (Excel) or a students[2:4, ] # Rows 2 to 4
database table. Data Frames in R are tabular
3. By column names
data structures that allow
Data frames are the most commonly storage of heterogeneous data
used data structure in data analysis students[ , "Marks"]
types across columns. They are
with R. essential for data manipulation,
Useful Functions for Data Frames
exploration, and modeling.
Creating a Data Frame
Function Description Functions in R
A function in R is a block of 1. Function without arguments # Anonymous function inside apply()
reusable code that performs a specific
task. greet <- function() { sapply(1:5, function(x) x^2)
Types of Functions
power(4) # 16 (default square) Breaking large programs
into smaller modular units.
Built-in Functions power(4, 3) # 64
Functions already provided by R. Performing repeated tasks
Examples: efficiently.
4. Function returning multiple
values
sum(c(2, 3, 5)) # 10
Used in data cleaning,
calculate <- function(a, b) { analysis, visualization,
mean(c(10, 20, 30)) # 20
modeling.
sum_val <- a + b
sqrt(25) #5
prod_val <- a * b
User-defined Functions Control Structures in R
Functions created by the user for
return(list(Sum = sum_val, Product =
specific tasks.
prod_val)) Control Structures in R are
statements that control the flow of
# Example: Function to calculate
} execution in a program.
square
They help in decision-making and
repetition of tasks, making R
square <- function(x) { programs more flexible and powerful.
calculate(4, 5)
return(x^2)
Types of Control Structures
# Output: $Sum = 9, $Product = 20
} 1. Conditional Statements
Anonymous Functions (Lambda
Functions) (a) if statement
square(6) # Output: 36
In R, we can create functions without Executes a block of code only if a
names, often used in quick operations. condition is TRUE.
Examples of User-defined Functions
Syntax: } else { result <- switch(operation,
repeat { }
Debugging and Simulation in R
print(i) test_fun(4)
R provides powerful features for
i <- i + 1 debugging programs and running debug() and undebug()
simulations. Debugging helps identify Runs functions in debug mode.
if (i > 5) { and fix errors in code, while
simulation allows modeling real-world debug(sum)
break processes using random numbers and
probability distributions. sum(1:5)
}
Debugging in R undebug(sum)
}
Debugging is the process of detecting, recover()
3. Loop Control Statements analyzing, and fixing errors (bugs) in Helps navigate through error
R programs to ensure correct locations in nested functions.
execution.
break → exits from a loop
immediately. options(error = recover)
Common Errors in R
try() and tryCatch()
next → skips the current 1. Syntax Errors – Errors in Helps handle errors without
iteration and moves to the typing commands. stopping the program.
next.
o Example: x <- result <- try(log("text"),
Example: c(1 2 3) → silent=TRUE)
missing comma.
for (i in 1:10) {
print("Program continues despite
2. Runtime Errors – Occur error")
if (i == 5) { while executing (e.g.,
invalid operation).
next # skip printing 5
o Example: tryCatch(
} dividing by zero.
{ log("abc") },
if (i == 8) { 3. Logical Errors – Code
runs but produces incorrect error = function(e) {
break # stop loop at 8 results. print("Caught an error!") }
} Debugging Tools in R )
print(i) traceback() Simulation in R
Shows the sequence of function
} calls after an error. Simulation is the process of
generating artificial data using random
Applications of Control Structures f <- function(x) { g(x) } numbers to model real-life phenomena
in R
or test statistical methods.
g <- function(y) { stop("Error in
g()") } Applications of Simulation
Testing algorithms and Simulation in R models real-world
models. processes using probability
distributions (runif(), rnorm(),
Predicting outcomes under
rbinom()), and methods like Monte
Carlo.
uncertainty.
Together, debugging ensures
Monte Carlo methods correctness of code, while simulation
(repeated random provides insights into uncertain
sampling). systems.
sample(1:10, 5, replace=TRUE)
rpois(5, lambda=3) #
Poisson
rexp(5, rate=1) #
Exponential
N <- 100000
pi_estimate
Predictive Modeling
Predictive modeling is a statistical and machine learning approach used to analyze historical
data and make forecasts about future events. It involves building mathematical models that
identify patterns and relationships between input variables (independent variables) and output
variables (dependent variables).
The core idea is: 'If we know how things behaved in the past, we can predict how they will
behave in the future.'
Predictive models may use statistical techniques such as linear regression, logistic regression,
decision trees, random forests, or neural networks depending on the complexity of the data
and the problem.
Purpose
The main purposes of predictive modeling include:
1. Forecasting – Estimating continuous numerical outcomes (e.g., predicting sales,
temperature, or revenue).
2. Classification – Determining categories or classes (e.g., whether a customer will buy a
product – Yes/No).
3. Risk Assessment – Measuring the likelihood of future events such as fraud detection, loan
defaults, or insurance claims.
4. Decision Support – Helping businesses and governments make better decisions using data-
driven insights.
Linear Regression
Linear regression is a statistical and machine learning technique used to model the
relationship between a dependent variable (Y) and one or more independent variables (X). It
assumes that this relationship can be represented using a straight line (linear relationship).
Y = β₀ + β₁X + ε
Where:
- Y = Dependent variable (the outcome we want to predict)
- X = Independent variable (the predictor or input)
- β₀ = Intercept (value of Y when X = 0)
- β₁ = Slope coefficient (how much Y changes for one unit increase in X)
- ε = Error term (difference between actual and predicted values, accounts for
randomness/noise)
Suppose we are predicting house price (Y) using house size (X).
Simple Linear Regression (SLR) is a statistical technique that uses one independent variable
(X) to predict the value of a dependent variable (Y). It assumes a linear relationship between
X and Y. The goal is to find the best-fitting straight line that represents the relationship
between the two variables.
1. Data Collection – Gather relevant data that contains both independent and dependent
variables.
Example: Salaries (Y) vs. Years of Experience (X).
2. Exploratory Analysis – Visualize the data using scatter plots to check whether a linear
pattern exists.
3. Model Fitting – Fit a regression line using the Least Squares Method, which minimizes the
error between actual and predicted values.
Score = 20 + 5 × 6 = 50
So, if a student studies for 6 hours, the predicted exam score is 50 marks.
Definition
Multiple Linear Regression (MLR) is an extension of simple linear regression where the
dependent variable (Y) is predicted using two or more independent variables (X₁, X₂, X₃, …,
Xn). It helps to understand how different factors collectively influence an outcome.
Unlike simple linear regression (which uses only one predictor), MLR considers multiple
predictors simultaneously, making the model more realistic for solving real-world problems.
Where:
- Y = Dependent variable (the output we want to predict)
- X₁, X₂, …, Xn = Independent variables (inputs or predictors)
- β₀ = Intercept (value of Y when all X = 0)
- β₁, β₂, …, βn = Coefficients (indicate how much Y changes when a specific X increases by
1, keeping other variables constant)
- ε = Error term (difference between actual and predicted values)
2. Fit a regression plane (or hyperplane in higher dimensions) that best represents the data.
3. The model estimates coefficients (β values) that minimize the difference between actual
and predicted values using the Least Squares Method.
4. Evaluate the accuracy using metrics such as R², Adjusted R², RMSE, and MAE.
Equation (trained model): Price = 30,000 + 150 × Size + 20,000 × Bedrooms + 10,000 ×
Location
Simulation in R
Simulation in R refers to the process of generating artificial (random) data to represent real-
world scenarios. It helps in studying system behavior, testing models, and analyzing
outcomes under different conditions.
Example: Instead of collecting marks from students, we can simulate exam scores using
probability distributions.
Importance of Simulation
1. Classification
Classification is a supervised learning technique used to predict qualitative (categorical)
outcomes. It classifies data into predefined categories such as spam/not spam, disease/no
disease, or pass/fail. The goal is to learn a decision boundary that separates classes.
Types of Classification:
Classification Process:
1. Collect and label dataset.
Logistic Regression, KNN, Naive Bayes, Decision Trees, Random Forest, SVM, Neural
Networks.
Applications:
2. Performance Measures
Performance metrics evaluate the effectiveness of classification models.
Confusion Matrix:
TP – True Positive
TN – True Negative
FP – False Positive
FN – False Negative
3. Logistic Regression
Logistic Regression is used for binary classification. It predicts probability using the
sigmoid function:
Decision rule:
If h(x) > 0.5 → Class 1
If h(x) < 0.5 → Class 0
Log-Odds:
log(p / (1 – p)) = b0 + b1x
Assumptions:
- Binary dependent variable
- No multicollinearity
- Linearity in log-odds
- Independent observations
Applications:
Medical diagnosis, credit scoring, fraud detection, marketing analysis.
R Implementation:
model <- glm(Species ~ [Link] + [Link], data=iris_binary, family=binomial)
Explanation:
We are creating a logistic regression model and saving it in the variable model.
glm() is the function used to build the model.
Species ~ [Link] + [Link] means:
o Species is what we want to predict.
o We are using Sepal Length and Sepal Width to make the prediction.
data = iris_binary means the model uses the dataset called iris_binary.
family = binomial tells R to perform logistic regression (because the output has
two classes: 0 or 1).
4. K-Nearest Neighbours (KNN)
KNN is a non-parametric, instance-based algorithm. Classification is based on majority
voting of K nearest neighbors.
Process:
1. Choose value of K.
2. Compute Euclidean distance.
3. Select K nearest points.
Advantages:
Simple, no training phase, effective for small datasets.
Disadvantages:
R Example:
pred <- knn(train[,1:4], test[,1:4], train$Species, k=3)
Explanation:
We are using the KNN algorithm to predict the species of flowers in the test
data.
train[,1:4] → the input features from training data
test[,1:4] → the input features from test data
train$Species → the correct species of the training flowers
k=3 → the algorithm looks at the 3 nearest neighbors to decide the class
The predicted species are stored in pred.
Steps:
1. Choose K.
2. Initialize centroids.
3. Assign points to nearest centroid.
4. Recalculate centroids.
Objective:
Minimize within-cluster sum of squares.
Applications:
R Example:
km <- kmeans(iris[,1:4], centers=3)
2. centers = 3
We are asking k-means to create 3 clusters.
Because the iris dataset has 3 types of flowers.
3. km <-
Stores the clustering result (cluster numbers, centers, etc.) in km.
6. Time Series Analysis
Time series is a sequence of observations recorded over time.
Components:
- Trend: Long-term direction.
- Seasonality: Regular repeating patterns.
- Cyclic variations.
- Random noise.
Models:
R Example:
model <- [Link](AirPassengers)
1. [Link]()
Automatically checks many ARIMA models.
Selects the best one based on accuracy.
Saves you from manually testing p, d, q values.
2. AirPassengers
A built-in time series dataset in R.
3. model <-
Saves the final selected ARIMA model into the variable model.
7. Social Network Analysis
Social Network Analysis (SNA) is a method used to study the relationships,
connections, and interaction patterns among individuals, groups, or organizations.
It represents these relationships as nodes (people or objects) and edges (connections or
interactions).
SNA helps understand how information flows, who is influential, how communities are
formed, and how groups behave.
Example
Consider a WhatsApp group:
Each member is a node
Each message or interaction between members is an edge
A person who talks to most people has high degree centrality
A person who connects two sub-groups has high betweenness centrality
This small social network can be analyzed to find influencers and communication
patterns.
e) Education
f) Marketing
statnet
sna
In Python
NetworkX
Graph-tool
PyVis
Definition
Reading data from MySQL in R means connecting R to a MySQL database and
importing tables into R for data analysis.
This is done using a database connection package such as RMySQL or DBI.
Explanation of Code
library(RMySQL)
user='root',
password='1234',
dbname='company')
1. library(RMySQL)
– Loads the RMySQL package so R can talk to MySQL.
2. dbConnect()
– Creates a connection between R and the MySQL server.
– You give username, password, and database name.
3. dbGetQuery()
– Sends an SQL query to MySQL.
– Here, "SELECT * FROM employees" means:
Get all the rows and columns from the employees table.
4. data
– Stores the imported table as a data frame in R.
Example:
Suppose we have a MySQL database company with a table employees:
id name salary
1 Mani 50000
2 Nandini 60000
After running:
Advantages:
1. Fast data transfer from MySQL to R.
2. Can run SQL queries directly in R.
3. Good for large datasets stored in databases.
4. Secure connection using username & password.
5. Useful for real-time data analysis.
Disadvantages:
1. Requires MySQL installed and running.
2. Passwords in code may be unsafe if not handled carefully.
3. RMySQL package may need additional configuration on some systems.
4. Large queries may take time or cause memory usage in R.
Applications:
1. Business data analysis (sales, employees, inventory).
Tools Used
RMySQL (R package)
MySQL Server
MySQL Workbench (optional)
RStudio (for writing R code)
Definition
Reading data from MongoDB in R means using R to connect to a MongoDB NoSQL
database and import collections (documents) into R for data analysis.
We commonly use the mongolite package in R to do this.
Simple Explanation
MongoDB stores data as documents (JSON-like format) instead of tables.
To read data from MongoDB into R:
1. Connect to MongoDB
Example Code :
library(mongolite)
Step-by-step Explanation
library(mongolite)
Loads the MongoDB package in R.
mongo(...)
Connects R to MongoDB.
o collection = "employees" → choose the collection
o db = "company" → choose the database
o url = "mongodb://localhost" → MongoDB runs on local system
conn$find()
Means:
Get all documents from the employees collection
and store them in R as a data frame.
Example
Suppose MongoDB contains:
id name salary
1 Mani 50000
2 Nandini 60000
Advantages
1. Easy handling of JSON-like data.
2. Great for unstructured or semi-structured data.
3. Fast reading and writing operations.
4. Flexible queries using MongoDB syntax.
5. Scales well for large data.
Disadvantages
1. Needs MongoDB installed and running.
2. No fixed schema → may cause inconsistent data.
3. Large collections may need powerful memory in R.
4. Fewer R packages available compared to SQL.