0% found this document useful (0 votes)
6 views14 pages

R Programming Notes

The document provides an overview of statistics and probability, emphasizing their importance in data analysis and decision-making. It details how to implement statistical methods in R, including descriptive and inferential statistics, probability calculations, and data visualization techniques. Additionally, it explains key statistical concepts such as mean, median, variance, and standard deviation, along with practical examples of their application in R.

Uploaded by

prithvivhegde
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)
6 views14 pages

R Programming Notes

The document provides an overview of statistics and probability, emphasizing their importance in data analysis and decision-making. It details how to implement statistical methods in R, including descriptive and inferential statistics, probability calculations, and data visualization techniques. Additionally, it explains key statistical concepts such as mean, median, variance, and standard deviation, along with practical examples of their application in R.

Uploaded by

prithvivhegde
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

Set of Statistical tables:

Statistics is a branch of mathematics and a scientific discipline that deals with the collection, analysis,
interpretation, presentation, and organization of data. It plays a crucial role in understanding and
summarizing information from data, making decisions, and drawing inferences or conclusions based on
empirical evidence.

Now, let's discuss how you can implement statistics in R:


Descriptive Statistics:
You can calculate basic descriptive statistics such as mean, median, and standard deviation using functions
like mean(), median(), and sd().
To summarize data, you can use the summary() function.

Inferential Statistics:
Hypothesis testing is a fundamental concept. Functions like [Link]() are used for t-tests, and [Link]() is
used for chi-squared tests. To calculate confidence intervals, you can use confint().

Probability:
You can calculate probabilities using functions like dbinom() for the binomial distribution, dnorm() for the
normal distribution, and so on.

Data Distributions:
R provides functions to work with various probability distributions, such as rnorm() for random numbers
from a normal distribution and rpois() for random numbers from a Poisson distribution.

Statistical Tests:
R has built-in functions for performing various statistical tests, such as [Link]() for t-tests and [Link]() for
chi-squared tests.

Statistical Models:
Linear regression can be performed using lm(). Logistic regression is implemented using glm().
Time series analysis can be done using packages like forecast and stats.

Probability is a fundamental concept in mathematics and statistics that quantifies the likelihood of an event
or outcome occurring. It's expressed as a value between 0 (impossible event) and 1 (certain event).
Probability theory is widely used in various fields, including statistics, to model uncertainty and make
predictions.

In R, you can implement probability in several ways, such as calculating probabilities, simulating random
events, and working with probability distributions. Here are some common aspects of probability and how
they can be implemented in R:

Calculating Probabilities:
You can calculate probabilities for specific events or outcomes using functions related to probability
distributions. Here's an example using the binomial distribution:
# Probability of getting exactly 3 heads in 5 coin flips
prob_3_heads <- dbinom(3, size = 5, prob = 0.5)
In this example, dbinom() calculates the probability of getting 3 heads in 5 flips of a fair coin with a
probability of success (heads) of 0.5.

1|R @prasan Unit3


Simulating Random Events:
R allows you to simulate random events based on probability distributions. For example, to simulate 100
random coin flips:
# Simulate 100 random coin flips (0 for tails, 1 for heads)
coin_flips <- rbinom(100, size = 1, prob = 0.5)
In this case, rbinom() generates 100 random values based on a binomial distribution with a probability of 0.5.

Probability Distributions:
R provides functions for working with various probability distributions, including:
dbinom(): Binomial distribution
dnorm(): Normal distribution
dpois(): Poisson distribution
dchisq(): Chi-squared distribution
dt(): Student's t-distribution
You can use these functions to calculate probabilities (PDFs) and cumulative probabilities (CDFs) for specific
values.

Probability Rules and Operations:


You can perform operations involving probabilities, such as calculating joint probabilities, conditional
probabilities, and using probability rules (e.g., the addition rule and multiplication rule). These calculations
can be implemented in R using basic arithmetic operations and functions.

Statistical Inference:
Probability theory is the foundation for statistical inference. You can perform hypothesis tests, calculate
confidence intervals, and make statistical predictions using the principles of probability.

Statistics and probability


Statistics and probability are closely related fields, and statistics can be used to analyze data and make
inferences about probabilistic events. Both are important fields in data analysis, and R is a popular
programming language and environment for working with data. Here are some ways to use statistics for
probability:

Installing and Loading Packages:


To perform statistical and probabilistic analysis, you may need to load specific packages. The two most
common packages for this purpose are stats and distributions.

# Install packages (only needed once)


[Link]("stats")
[Link]("distributions")
# Load packages
library(stats)
library(distributions)

Descriptive Statistics:
Descriptive statistics are used to summarize and describe data. Common measures of central tendency (e.g.,
mean, median, mode) and measures of dispersion (e.g., variance, standard deviation, range) provide insights
into the characteristics of a dataset. These statistics help describe the probability distribution of the data.
You can compute basic statistics like mean, median, variance, and standard deviation using R. For example,
to calculate the mean of a vector x:
x <- c(1, 2, 3, 4, 5)
mean_x <- mean(x)

2|R @prasan Unit3


Probability Distributions:
In statistics, you often work with different probability distributions, such as the normal distribution, binomial
distribution, Poisson distribution, and more. These distributions model the probabilities of various events
and outcomes, making them fundamental for understanding and making probabilistic predictions.

R provides functions to work with various probability distributions. For instance, to generate random
numbers from a normal distribution:
# Generate 100 random numbers from a normal distribution with mean 0 and standard deviation 1
random_numbers <- rnorm(100, mean = 0, sd = 1)
You can similarly use dnorm() for the probability density function (PDF), pnorm() for the cumulative
distribution function (CDF), and qnorm() for the quantile function.
Probability Density Functions (PDF) and Cumulative Distribution Functions (CDF), These functions are used
to describe the probabilities associated with continuous random variables. The PDF describes the probability
of a random variable taking on a specific value, while the CDF describes the probability that the random
variable is less than or equal to a given value.

Hypothesis Testing:
Statistics is used to perform hypothesis tests, which involve making probabilistic decisions based on data.
You can test hypotheses about population parameters, compare groups, and assess the likelihood of
observed data under different hypotheses.
R allows you to perform hypothesis tests. For example, to perform a t-test on two samples:
# Generate two sample data
group1 <- c(22, 24, 26, 28, 30)
group2 <- c(18, 20, 22, 24, 26)
# Perform a two-sample t-test
t_test_result <- [Link](group1, group2)

Linear Regression:
Regression analysis is used to model and analyze the relationships between variables. It involves estimating
parameters that provide insights into the probabilities and impacts of one variable on another. For example,
linear regression estimates the relationship between a dependent variable and one or more independent
variables.
You can perform linear regression to model the relationship between variables. For example:
# Create a data frame
data <- [Link](x = c(1, 2, 3, 4, 5), y = c(2, 4, 5, 4, 6))
# Fit a linear regression model
lm_model <- lm(y ~ x, data = data)
# Summary of the model
summary(lm_model)

Probability Calculations:
R is useful for calculating probabilities, such as calculating the probability of an event occurring in a binomial
distribution:
# Probability of getting exactly 3 heads in 5 coin flips
prob_3_heads <- dbinom(3, size = 5, prob = 0.5)

Data Visualization:
To visualize your data and statistical results, you can use various packages like ggplot2 and base R graphics.
# Load ggplot2
library(ggplot2)
# Create a scatter plot
ggplot(data, aes(x, y)) + geom_point()

3|R @prasan Unit3


Statistical Tests and Models:
R provides functions for a wide range of statistical tests and models, such as ANOVA, chi-squared tests,
logistic regression, and more. You can explore these based on your specific analysis needs.

Process of Descriptive analysis: Refers to the process of summarizing and exploring a dataset to gain a
better understanding of its basic characteristics. The primary objective of descriptive analysis is to describe
and visualize the data in a way that helps researchers or analysts recognize patterns, trends, and important
features. This analysis provides a foundation for more advanced statistical analysis and hypothesis testing.

One general example:


# Load the dataset (e.g., from a CSV file)
data <- [Link]("your_dataset.csv")
# Display the first few rows of the dataset
head(data)
# Generate summary statistics for numeric variables
summary(data)
# Create a histogram of a numeric variable
library(ggplot2)
ggplot(data, aes(x = Age)) +
geom_histogram(binwidth = 5, fill = "blue", color = "black") +
labs(title = "Age Distribution", x = "Age", y = "Frequency")
# Check for missing values
missing_values <- sum([Link](data$Income))
# Create a frequency table for a categorical variable
table(data$Category)

Here's a step-by-step process of performing descriptive analysis in R, along with an example:

Step 1: Load Data:


First, you need to load your dataset into R. You can use functions like [Link](), [Link](), or specific data
import functions based on your data format.
# Load a dataset (e.g., a CSV file)
data <- [Link]("your_dataset.csv")

Step 2: Explore the Data:


Once you have your data loaded, you should explore it to get a sense of what's inside. Common functions
and techniques include:
head(data): Display the first few rows of the dataset to get a quick overview.
summary(data): Generate a summary of numeric variables, including mean, median, min, max, and quartiles.
str(data): Display the structure of the dataset, showing variable types.
table(data$column): Create frequency tables for categorical variables.

# Display the first few rows of the dataset


head(data)
# Generate summary statistics for numeric variables
summary(data)
# Display the structure of the dataset
str(data)
# Create a frequency table for a categorical variable
table(data$Category)

4|R @prasan Unit3


Step 3: Visualize the Data:
Data visualization is an essential part of descriptive analysis. You can create plots to better understand your
data distribution and relationships. Common plotting packages in R include ggplot2, base R graphics, and
lattice.

# Load the ggplot2 package


library(ggplot2)
# Create a histogram of a numeric variable
ggplot(data, aes(x = Age)) +
geom_histogram(binwidth = 5, fill = "blue", color = "black") +
labs(title = "Age Distribution", x = "Age", y = "Frequency")

Step 4: Calculate Descriptive Statistics


You can calculate descriptive statistics for numeric variables using functions like mean(), median(), sd()
(standard deviation), and var() (variance).

# Calculate the mean and median of a numeric variable


mean_age <- mean(data$Age)
median_age <- median(data$Age)
# Calculate the standard deviation and variance
std_dev_age <- sd(data$Age)
var_age <- var(data$Age)

Step 5: Handle Missing Data


Check for missing values in your dataset and decide how to handle them. You can use functions like [Link]()
and [Link]() to identify and filter out missing values.

# Check for missing values


missing_values <- sum([Link](data$Income))
# Filter out rows with missing values
data_clean <- data[[Link](data), ]

Step 6: Summarize Findings


Finally, summarize your findings based on the exploratory analysis. You can create a report, present
visualizations, and highlight key statistics and insights from your data.

Average (Mean), Variance, and Standard Deviation are fundamental statistical measures used to
describe the central tendency and variability of a dataset.

Average (Mean):
The mean is a measure of central tendency that represents the typical value in a dataset.
It is calculated by summing all values in a dataset and dividing by the total number of values.
 The average, also known as the mean, is a measure of central tendency.
 It represents the "typical" value in a dataset.
 To calculate the mean, you sum up all the values in the dataset and then divide by the total number
of values.
 Formula: Mean = (Sum of all values) / (Number of values).
 The mean is sensitive to extreme values (outliers).

5|R @prasan Unit3


In R, you can calculate the mean using the mean() function:

# Example dataset
data <- c(10, 15, 20, 25, 30)
# Calculate the mean
mean_value <- mean(data)

Variance:
Variance is a measure of how much individual data points deviate from the mean. It quantifies the spread or
dispersion of data.
 Variance is a measure of the spread or dispersion of data points in a dataset.
 It quantifies how much individual data points deviate from the mean.
 A high variance indicates that the data points are spread out over a wider range.
 Formula: Variance = (Sum of the squared differences from the mean) / (Number of values - 1).
 Variance is always a non-negative value.
It is calculated by taking the average of the squared differences between each data point and the mean.
In R, you can calculate the variance using the var() function:

# Example dataset
data <- c(10, 15, 20, 25, 30)
# Calculate the variance
variance_value <- var(data)

Standard Deviation:
The standard deviation is a measure of the typical or average amount of deviation of data points from the
mean.
The standard deviation is closely related to the variance and measures the average amount of variation or
dispersion in a dataset.

 It is the square root of the variance.


 The standard deviation provides a measure of the "typical" or "average" amount of deviation of data
points from the mean.
 Formula: Standard Deviation = √(Variance).
 It shares the same units as the data, making it more interpretable than the variance.
 It is the square root of the variance and shares the same units as the data, making it more
interpretable.
In R, you can calculate the standard deviation using the sd() function:

# Example dataset
data <- c(10, 15, 20, 25, 30)
# Calculate the standard deviation
std_deviation_value <- sd(data)

Now, let's look at an example that calculates the mean, variance, and standard deviation of a dataset in R:
# Example dataset
data <- c(10, 15, 20, 25, 30)
# Calculate the mean # Print the results
mean_value <- mean(data) cat("Mean:", mean_value, "\n")
# Calculate the variance cat("Variance:", variance_value, "\n")
variance_value <- var(data) cat("Standard Deviation:", std_deviation_value, "\n")
# Calculate the standard deviation
std_deviation_value <- sd(data)

6|R @prasan Unit3


Mean, Median, and Mode: are measures of central tendency in statistics. They are used to describe the
center or typical value of a dataset, and they provide insights into the distribution of the data:

Mean:
The mean, also known as the average, is the sum of all values in a dataset divided by the total number of
values. It represents the arithmetic center of the data.
 The mean is sensitive to outliers or extreme values because it takes into account the magnitude of all
data points.
 Formula: Mean = (Sum of all values) / (Number of values)
 The mean, or average, is calculated by summing all values in a dataset and dividing by the total
number of values. It represents the arithmetic center of the data.
 Mean is sensitive to outliers, as it takes into account the magnitude of all data points.
In R, you can calculate the mean using the mean() function:

# Example dataset
data <- c(10, 15, 20, 25, 30)
# Calculate the mean
mean_value <- mean(data)

Median:
The median is the middle value in a dataset when the data is ordered from smallest to largest. If there is an
even number of values, the median is the average of the two middle values.
 It is a measure of the central position that is not affected by extreme values (outliers).
 The median is the middle value in a dataset when the data is ordered from smallest to largest. If
there is an even number of values, the median is the average of the two middle values.
 Median is less affected by outliers compared to the mean.
In R, you can calculate the median using the median() function:

# Example dataset
data <- c(10, 15, 20, 25, 30)
# Calculate the median
median_value <- median(data)

Mode:
The mode is the value that appears most frequently in a dataset.
 A dataset can have one mode (unimodal), multiple modes (multimodal), or no mode at all.
 It is often used for categorical or discrete data, but it can also be applied to continuous data.
 Mode is often used for categorical or discrete data.

Example dataset: 2, 3, 3, 5, 6, 7, 7, 9
Mean: (2 + 3 + 3 + 5 + 6 + 7 + 7 + 9) / 8 = 42 / 8 = 5.25
Median: Since there are 8 values, the median is the average of the 4th and 5th values: (5 + 6) / 2 = 5.5
Mode: The mode is 3 and 7 because they both occur twice, making this dataset bimodal.

# Example dataset # In the example, we've used a custom function to


data <- c(2, 3, 3, 5, 6, 7, 7, 9) calculate the mode since R doesn't have a built-in
mode function.
# Custom function to calculate the mode
calculate_mode <- function(x) { # Calculate the mode
unique_x <- unique(x) mode_value <- calculate_mode(data)
unique_x[[Link](tabulate(match(x, unique_x)))]
}

7|R @prasan Unit3


Covariance and correlation: are both measures used in statistics to describe the relationship between two
or more variables in a dataset. They provide insights into how variables change together and to what extent
they are related. Here's an explanation of each:

Covariance:
Covariance is a measure of the degree to which two variables change together.
It indicates the direction of the linear relationship between two variables.
A positive covariance means that as one variable increases, the other tends to increase as well, and as one
decreases, the other tends to decrease. A negative covariance means they move in opposite directions.
The magnitude of covariance is not standardized, so it's challenging to compare covariance between
different datasets. It depends on the units of the variables involved.
Formula for the sample covariance between two variables X and Y:
Cov(X, Y) = Σ [(Xᵢ - X) * (Yᵢ - Ȳ)] / (n - 1)
Xᵢ and Yᵢ are data points.
X and Ȳ are the means of X and Y, respectively.
n is the number of data points.

To calculate the covariance between two variables in R, you can use the cov() function. Here's an example:
# Example dataset
x <- c(2, 4, 6, 8, 10)
y <- c(1, 3, 5, 7, 9)
# Calculate the covariance between x and y
covariance_value <- cov(x, y)
# Print the covariance
cat("Covariance:", covariance_value, "\n")

Correlation:
Correlation is a standardized measure that quantifies the strength and direction of the linear relationship
between two variables.
It scales the covariance by the standard deviations of the variables, resulting in values between -1 and 1.
A correlation of 1 indicates a perfect positive linear relationship, -1 indicates a perfect negative linear
relationship, and 0 indicates no linear relationship.
Correlation is not affected by the scale or units of the variables, making it more interpretable and
comparable than covariance.
Formula for the sample correlation coefficient (Pearson correlation) between X and Y:
Cor(X, Y) = Cov(X, Y) / (σₓ * σᵧ)
Cov(X, Y) is the covariance between X and Y.
σₓ and σᵧ are the standard deviations of X and Y, respectively.

To calculate the correlation between two variables in R, you can use the cor() function. Here's an example:
# Example dataset
x <- c(2, 4, 6, 8, 10)
y <- c(1, 3, 5, 7, 9)
# Calculate the correlation between x and y
correlation_value <- cor(x, y)
# Print the correlation
cat("Correlation:", correlation_value, "\n")

In this example, we calculate the correlation between the same variables x and y. The cor() function returns
the correlation value, which is a standardized measure that quantifies the strength and direction of the linear
relationship between the two variables. A value of 1 indicates a perfect positive linear relationship, -1
indicates a perfect negative linear relationship, and 0 indicates no linear relationship.

8|R @prasan Unit3


Probability distribution is a mathematical function or model that describes how the possible outcomes of
a random variable are distributed or the likelihood of those outcomes occurring. In other words, it specifies
the probabilities associated with each possible value of a random variable.

Probability distributions are fundamental in statistics and probability theory and are used to model a wide
range of real-world phenomena, from the outcomes of rolling dice to the measurements of physical
quantities.

Some common probability distributions and their applications include:


Normal distribution: Used to model many real-world measurements, such as heights and IQ scores.
Exponential distribution: Often used to model the time between events in a Poisson process, such as the
time between arrivals of customers at a service center.
Binomial distribution: Used to model the number of successes in a fixed number of Bernoulli trials.
Poisson distribution: Appropriate for modeling rare events, such as the number of phone calls arriving at a
call center in a given minute.

Normal distribution: also known as a Gaussian distribution, is a continuous probability distribution that is
symmetric and bell-shaped. In a normal distribution, the data is centered around a mean (average) value,
and it follows a specific pattern where most of the data points are close to the mean, and as you move away
from the mean, the number of data points decreases symmetrically. The properties of the normal
distribution are well-defined, and it is widely used in statistics and data analysis.

The probability density function (PDF) of a normal distribution is given by the formula:

Normal distribution examples list:

Height of a Population:
Human height tends to follow a normal distribution, with most people clustered around the average height.
IQ Scores:
Intelligence Quotient (IQ) scores are often modeled as normally distributed with a mean of 100.
Body Temperature:
Human body temperature is approximately normally distributed with a mean around 98.6°F (37°C).
Exam Scores:
In large populations, exam scores often exhibit a normal distribution.
Weight of Newborns:
Birth weights of newborns are often normally distributed.
Errors in Measurements:
Errors in measurements and experimental data often follow a normal distribution.
Blood Pressure:
Blood pressure measurements in a population tend to have a normal distribution.

9|R @prasan Unit3


Income Distribution:
In some cases, the distribution of incomes in a population can be approximated by a normal distribution.
Residuals in Regression Analysis:
Residuals from a regression analysis are often assumed to be normally distributed.
Reaction Times:
The time it takes for individuals to react to a stimulus is often modeled as a normal distribution.
Stock Prices:
Daily stock price changes often exhibit a distribution that is close to normal.
Test Scores:
Standardized test scores, such as SAT or GRE scores, often follow a normal distribution.

Normal distribution is widely used in statistics and provides a convenient way to model a variety of
phenomena in the natural and social sciences. It's important to note that not all real-world phenomena
follow a perfect normal distribution, but many approximate it well.

In R, you can work with normal distributions using the dnorm(), pnorm(), qnorm(), and rnorm() functions.
Here's an explanation and an example of a normal distribution in R:

dnorm() - Probability Density Function (PDF):


dnorm(x, mean, sd) calculates the PDF value at a specific point x with a given mean and standard deviation.
Example:
# Calculate the PDF at x = 2 for a normal distribution with mean 0 and standard deviation 1
pdf_value <- dnorm(2, mean = 0, sd = 1)
print(pdf_value)

pnorm() - Cumulative Distribution Function (CDF):


pnorm(x, mean, sd) calculates the probability that a random variable from a normal distribution is less than
or equal to x. Example:
# Calculate the CDF value at x = 1 for a normal distribution with mean 0 and standard deviation 1
cdf_value <- pnorm(1, mean = 0, sd = 1)
print(cdf_value)

qnorm() - Quantile Function:


qnorm(p, mean, sd) calculates the quantile (inverse CDF) of a normal distribution at a specific probability p.
Example:
# Calculate the quantile for p = 0.975 for a normal distribution with mean 0 and standard deviation 1
quantile_value <- qnorm(0.975, mean = 0, sd = 1)
print(quantile_value)

rnorm() - Random Number Generation:


rnorm(n, mean, sd) generates n random numbers from a normal distribution with a given mean and standard
deviation.
Example:
# Generate 10 random numbers from a normal distribution with mean 5 and standard deviation 2
random_numbers <- rnorm(10, mean = 5, sd = 2)
print(random_numbers)

The normal distribution is widely used in various statistical analyses, such as hypothesis testing, confidence
intervals, and modelling natural phenomena, where it serves as a useful approximation for many real-world
data sets.

10 | R @prasan Unit3
# Example: IQ Scores
[Link](123) # Setting seed for reproducibility

# Generate a sample of IQ scores (assuming a mean of 100 and standard deviation of 15)
iq_scores <- rnorm(1000, mean = 100, sd = 15)

# Calculate mean and standard deviation


mean_iq <- mean(iq_scores)
sd_iq <- sd(iq_scores)
cat("Mean IQ:", mean_iq, "\n")
cat("Standard Deviation IQ:", sd_iq, "\n")

# Calculate probability density function (pdf) at specific points


pdf_at_110 <- dnorm(110, mean = mean_iq, sd = sd_iq)
pdf_at_90 <- dnorm(90, mean = mean_iq, sd = sd_iq)
cat("PDF at IQ 110:", pdf_at_110, "\n")
cat("PDF at IQ 90:", pdf_at_90, "\n")

# Calculate cumulative distribution function (cdf) up to specific points


cdf_up_to_110 <- pnorm(110, mean = mean_iq, sd = sd_iq)
cdf_up_to_90 <- pnorm(90, mean = mean_iq, sd = sd_iq)
cat("CDF up to IQ 110:", cdf_up_to_110, "\n")
cat("CDF up to IQ 90:", cdf_up_to_90, "\n")

# Quantile function - find IQ score corresponding to a given percentile


iq_at_percentile <- qnorm(0.75, mean = mean_iq, sd = sd_iq)
cat("IQ score at the 75th percentile:", iq_at_percentile, "\n")

# Generate random IQ scores


random_iq_scores <- rnorm(10, mean = mean_iq, sd = sd_iq)
cat("Random IQ Scores:", random_iq_scores, "\n")

Binomial distribution is a discrete probability distribution that models the number of successes (usually
denoted as "x") in a fixed number of independent and identically distributed Bernoulli trials. Each Bernoulli
trial has only two possible outcomes, typically labeled as "success" and "failure." The probability of success is
denoted as "p," and the probability of failure is "1 - p."

The probability mass function (PMF) of a binomial distribution is given by the formula:

11 | R @prasan Unit3
Where:
x represents the number of successes.
n is the total number of trials.
p is the probability of success on a single trial.

Binomial distributions examples list: Binomial distributions are commonly used to model situations
involving a fixed number of trials with two possible outcomes (success or failure)

Coin Flipping:
Model the number of heads (successes) in a fixed number of coin flips.
Manufacturing Defects:
Determine the probability of a certain number of defective items in a batch produced with a known defect
rate.
Quality Control:
Estimate the probability of a specific number of defective products in a sample from a production line.
Biological Trials:
Analyze genetic crosses, where you might be interested in the number of offspring with a specific trait.
Survey Responses:
Model the number of respondents selecting a particular option in a multiple-choice question.
Loan Approvals:
Calculate the probability of a certain number of loan applications being approved given a fixed approval rate.
Call Center Response:
Predict the number of successful sales calls in a fixed number of attempts.
Website Click-Through Rates:
Estimate the probability of a certain number of clicks on an online advertisement in a fixed number of
impressions.
Clinical Trials:
Model the number of patients showing improvement in response to a new treatment.
Employee Attrition:
Predict the number of employees leaving a company within a fixed period.

In R, you can work with binomial distributions using the dbinom(), pbinom(), qbinom(), and rbinom()
functions. Here's an explanation and an example of a binomial distribution in R:

dbinom() - Probability Mass Function (PMF):


dbinom(x, size, prob) calculates the probability of getting exactly x successes in size trials with a success
probability of prob.
Example:
# Calculate the probability of getting exactly 3 heads in 5 coin flips (fair coin)
probability_3_heads <- dbinom(3, size = 5, prob = 0.5)
print(probability_3_heads)

pbinom() - Cumulative Distribution Function (CDF):


pbinom(x, size, prob) calculates the probability of getting at most x successes in size trials with a success
probability of prob.
Example:
# Calculate the probability of getting at most 3 heads in 5 coin flips (fair coin)
probability_at_most_3_heads <- pbinom(3, size = 5, prob = 0.5)
print(probability_at_most_3_heads)

qbinom() - Quantile Function:


qbinom(p, size, prob) calculates the quantile (number of successes) such that the probability of getting at
most x successes is p.

12 | R @prasan Unit3
Example:
# Calculate the number of coin flips required to have a 90% chance of getting at most 2 heads (fair coin)
num_flips_required <- qbinom(0.9, size = 5, prob = 0.5)
print(num_flips_required)

rbinom() - Random Number Generation:


rbinom(n, size, prob) generates n random numbers following a binomial distribution with parameters size
and prob.
Example:
# Generate 10 random numbers representing the number of successful coin flips (fair coin) in 5 trials
random_numbers <- rbinom(10, size = 5, prob = 0.5)
print(random_numbers)

Here's an example which demonstrating various aspects of the binomial distribution using the scenario of
coin flipping:

# Example: Coin Flipping


[Link](123) # Setting seed for reproducibility
# Simulate 20 coin flips with a fair coin (probability of success = 0.5)
num_flips <- 20
probability_success <- 0.5

# Generate binomial distribution


binomial_distribution <- rbinom(num_flips, size = 1, prob = probability_success)
# Display the simulated coin flips
cat("Simulated Coin Flips:", binomial_distribution, "\n")

# Calculate probability mass function (pmf) for specific outcomes


pmf_5_heads <- dbinom(5, size = num_flips, prob = probability_success)
pmf_10_heads <- dbinom(10, size = num_flips, prob = probability_success)
cat("PMF for getting exactly 5 heads:", pmf_5_heads, "\n")
cat("PMF for getting exactly 10 heads:", pmf_10_heads, "\n")

# Calculate cumulative distribution function (cdf) up to specific outcomes


cdf_up_to_5_heads <- pbinom(5, size = num_flips, prob = probability_success)
cdf_up_to_10_heads <- pbinom(10, size = num_flips, prob = probability_success)
cat("CDF up to getting 5 heads:", cdf_up_to_5_heads, "\n")
cat("CDF up to getting 10 heads:", cdf_up_to_10_heads, "\n")

# Quantile function - find the number of heads for a given cumulative probability
num_heads_at_cdf_0_75 <- qbinom(0.75, size = num_flips, prob = probability_success)
cat("Number of heads at the 75th percentile:", num_heads_at_cdf_0_75, "\n")

# Generate random outcomes for 10 trials


random_outcomes <- rbinom(10, size = num_flips, prob = probability_success)
cat("Random outcomes for 10 trials:", random_outcomes, "\n")

Stationary distribution for Markov Chain:


A transition matrix is a square matrix that represents the probabilities of transitioning from one set of states
to another in a system. It is commonly used in the context of Markov chains, which are mathematical models
used to describe a sequence of events where the probability of each event depends only on the state of the
system in the previous step.

13 | R @prasan Unit3
In a transition matrix:
Each row represents the current state of the system.
Each column represents the next possible state of the system.
The entries of the matrix represent the probabilities of transitioning from the current state to the next state.
For example, consider a simple weather model with states "Sunny," "Cloudy," and "Rainy." The transition
matrix might look like this:
S C R
0.7 & 0.2 & 0.1 \\
0.3 & 0.6 & 0.1 \\
0.2 & 0.3 & 0.5 \\
\end{bmatrix} \]
Here, the entry in the first row and first column (0.7) represents the probability of transitioning from "Sunny"
to "Sunny," the entry in the first row and second column (0.2) represents the probability of transitioning
from "Sunny" to "Cloudy," and so on.
Transition matrices are crucial for analyzing the dynamics and long-term behavior of Markov chains,
including finding stationary distributions and understanding how the system evolves over time.

Prog 6:
# Define the transition probability of stationary distribution matrix for the weather Markov chain
transition_matrix <- matrix(c(0.7, 0.2, 0.1,
0.3, 0.6, 0.1,
0.2, 0.3, 0.5), nrow = 3, byrow = TRUE)

# Display the transition matrix


cat("Transition Matrix:\n")
print(transition_matrix)
# Function to find the stationary distribution
# tol - This is the tolerance parameter.
find_stationary_distribution <- function(trans_matrix, tol = 1e-8, max_iter = 1000) {
n <- nrow(trans_matrix)
# rep - is a function call that generates a vector
# by repeating the value 1/n n times.
# Initial guess for stationary distribution
pi <- rep(1/n, n)
# print(pi)

for (iter in 1:max_iter) {


pi_prev <- pi
pi <- pi %*% trans_matrix
if (max(abs(pi - pi_prev)) < tol) {
cat("Converged after", iter, "iterations.\n")
return(pi)
}
}
warning("Stationary distribution did not converge within the specified number of iterations.")
return(NULL)
}

# Find the stationary distribution


stationary_distribution <- find_stationary_distribution(transition_matrix)

# Print the stationary distribution


cat("Stationary Distribution:\n")

14 | R @prasan Unit3

You might also like