R Programming
R Programming
Way Probability
1|Page
Tails 1/2 = 0.5
Event P(A)
2|Page
probability
Types of probability
Theotical probability
Experimental probability
Axiomatic probability
Defination: Probability distributions are functions that calculates the probabilities of the outcomes
of random variables.
Typical examples of random variables are coin tosses and dice rolls.
Example 1
Here is an graph showing the results of a growing number of coin tosses and the expected values of the
results (heads or tails). The expected values of the coin toss is the probability distribution of the coin
toss. Notice how the result of random coin tosses gets closer to the expected values (50%) as the
number of tosses increases.
3|Page
Example 2
Similarly, here is a graph showing the results of a growing number of dice rolls and the expected values
of the results (from 1 to 6). Notice again how the result of random dice rolls gets closer to the expected
values (1/6, or 16.666%) as the number of rolls increases.
Example 3
When the random variable is a sum of dice rolls the results and expected values take a different shape.
The different shape comes from there being more ways of getting a sum of near the middle, than a small
or large sum. Common Probability distribution functions.
• Binomial distribution
• Poisson distribution
• Uniform distribution
• Bernoulli distribution
• Rademacher distribution
• Normal distribution
• Exponential distribution
• Gamma distribution
A probability mass function differs from a probability density function (PDF) in that the latter is
associated with continuous rather than discrete random variables. A PDF must
be integrated over an interval to yield a probability.[2]
Bernoulli
BERNOULLI DISTRIBUTION
6|Page
The Bernoulli distribution is a discrete probability distribution that models a random experiment with
two possible outcomes: success (coded as 1) and failure (coded as 0). It is commonly used to represent
situations where an experiment results in a binary outcome, such as flipping a coin (heads or tails) or the
success or failure of a single trial in a binary experiment.
Probability Mass Function (PMF): The probability mass function (PMF) of a Bernoulli distribution
describes the probability of observing a particular outcome. For a random variable X with a Bernoulli
distribution: Here, p is the probability of success, and q is the probability of failure.
Key Properties:
Parameter p: The parameter p represents the probability of success in a single trial. Its range is
between 0 and 1.
1. The Bernoulli distribution is frequently used in machine learning and data analysis for binary
classification tasks. It can simulate the likelihood that a sample will fall into a specific class or category.
2. The Bernoulli distribution is used to model click-through rates (CTR) in online advertising and
marketing. The distribution can be used to calculate the likelihood that a user will click on an
advertisement or perform a particular activity.
3. To ascertain if a product or procedure complies with specific criteria, the Bernoulli distribution is used
in quality control. It is possible to utilize it to simulate the occurrence of flaws or failures.
4. When analyzing survey data, binary replies to questions with true/false or yes/no alternatives can be
modeled using the Bernoulli distribution. This makes it possible to estimate response probabilities and
compare proportions.
5. Clinical trials and epidemiological research are two examples of biological investigations that make
use of the Bernoulli distribution. It can simulate things like the onset of an illness, the efficacy or
inefficacy of treatments, or patient reactions.
6. In reliability engineering, binary events linked to system dependability, such as component failure or
system downtime, can be analyzed using the Bernoulli distribution.
7. The Bernoulli distribution is used to represent the probability of uncommon events or insurance
claims in risk assessment and insurance studies.
Summary:
7|Page
The Bernoulli distribution is a simple yet fundamental concept in probability theory. Understanding its
properties and implementing it in R enables you to model and analyze binary outcomes in various
applications. The provided R code snippets and visualizations should assist you in exploring and working
with the Bernoulli distribution effectively.
Binomial Distribution
The Binomial Distribution model is an essential part of statistical analysis that
provides powerful insights into probabilities and events. It is a discrete probability
distribution of the number of successes in independent experiments. We can
easily manipulate, analyze, and visualize these distributions by harnessing the
power of R, a popular language among statisticians and data scientists. This article
will delve into the theoretical underpinnings of the Binomial Distribution and its
applications and illustrate how to leverage R programming for implementing and
visualizing it.
The binomial is a distribution type with two possible outcomes (the prefix ‘bi’
represents two or twice). For example, a coin toss has two possible outcomes:
heads or tails.
8|Page
[Link] observations’ number or trials is fixed. In other words, you can only figure
out the probability of something happening if you do it a certain number of times.
These characteristics make the binomial distribution suitable for a wide range of
real-world scenarios and problems.
[Link] probability of success on a single trial is equal to p and remains the same
from trial to trial. The probability of failure is 1 – p = q.
We have seen that the number of ways of obtaining x successes in n trials is given
by:(n/x) =n! /x! (n-x) !.
[Link] Control in Manufacturing: A factory produces items and each item may
be defective or not defective. If you randomly select a certain number of items
(fixed number of trials), the binomial distribution can be used to calculate the
probability of finding a specific number of defective items. Each selection is an
independent event and the probability of selecting a defective item is the same
for each selection.
9|Page
[Link] Trials: Suppose a drug has a 70% chance of curing a certain disease. If
the drug is given to 50 patients (fixed number of trials), the binomial distribution
can help estimate the probability of the drug curing a certain number of patients.
Each patient’s outcome is independent of the others and the probability of
success (curing the disease) is the same for each trial.
[Link] Sampling: If you’re conducting a survey and you know that 60% of a
population will choose option A (based on past data or a larger sample), a
binomial distribution can help you determine the probability that a certain
number out of a smaller sample will choose option A. Each survey response is an
independent event, the probability of each person choosing option A is the same,
and you’re surveying a fixed number of people.
[Link]: If a basketball player makes a free throw 80% of the time, you can use
the binomial distribution to calculate the probability of that player making a
certain number of free throws out of a fixed number of attempts. Each free throw
is an independent event, and the probability of success is the same for each shot.
[Link] of Spam Emails per Day:Email companies use the binomial distribution
to model the probability that a certain number of spam emails land in an inbox
per day.
10 | P a g e
The binomial distribution is a discrete probability distribution that models the
number of successes in a fixed number of independent Bernoulli trials. A Bernoulli
trial is an experiment or process that results in a binary outcome, often termed
“success” or “failure”.
The probability mass function (PMF) of the binomial distribution is given by:
Where:
• pbinom()
• qbinom()
• rbinom()
dbinom()
The dbinom() function in R is a powerful tool for computing a binomial
distribution’s probability density (mass) function. It allows users to calculate the
probability of obtaining a specific number of “successes” in a fixed number of
Bernoulli trials, given a certain probability of success. By leveraging dbinom(),
users can enhance their statistical analysis, offering a clearer understanding of
binomial distributions in practical scenarios.
# Here we’re looking at a situation with 5 trials (let’s say flipping a coin 5 times),
# and we want to know the probability of getting 3 successes (let’s say 3 heads).
print(prob_three_heads)
12 | P a g e
The output for this code might look something like this:
[1] 0.3125
This suggests that the probability of getting exactly 3 heads in 5 coin tosses is
0.3125, assuming a fair coin (where the probability of getting a head in each toss
is 0.5).
Here’s another example using pbinom(), which gives us the cumulative probability
distribution, i.e., the probability of getting ‘x’ successes or fewer:
print(prob_five_or_less)
[1] 0.8823515
This indicates that the probability of getting 5 or fewer successes in 20 trials, with
the probability of success on each trial being 0.25, is approximately 0.882.
pbinom()
13 | P a g e
The pbinom() function in R calculates the cumulative probability of a binomial
distribution. This function is incredibly helpful when we need to compute the
probability of having a certain number of successes or fewer in a given number of
independent trials.
print(prob_four_or_less)
The 'q' parameter is the number of successes we're interested in, 'size' represents
the number of trials, and 'prob' is the probability of success on each trial.
[1] 0.6230469
This suggests that the probability of getting 4 heads or fewer in 10 coin tosses is
approximately 0.623, assuming a fair coin (where the probability of getting a head
in each toss is 0.5).
qbinom()
14 | P a g e
The qbinom() function in R provides the inverse of the pbinom() function. It
returns the smallest number of successes in a set of Bernoulli trials for which the
cumulative probability is greater than or equal to a specified probability level. In
other words, qbinom() is used for a binomial distribution to find the quantile
function, or the number of successes at a given percentile.
# and we want to know the number of successes (e.g., heads) we’d expect to see at
the 70th percentile.
print(num_successes)
[1] 6
This suggests that in 10 coin tosses, we’d expect to see 6 or fewer heads 70% of
the time, assuming a fair coin (where the probability of getting a head in each toss
is 0.5).
rbinom()
R’s rbinom() function allows us to generate random numbers following a binomial
distribution. This can be incredibly useful in various situations, such as simulating
experiments, bootstrapping, or validating statistical models.
15 | P a g e
# In this example, we want to generate 100 random numbers (let’s say 100
experiments of flipping a coin 10 times),
print(random_numbers)
In this code, ‘n’ is the number of random numbers we want to generate, ‘size’ is
the number of trials, and ‘prob’ is the probability of success on each trial.
[1] 5 6 5 4 5 4 6 7 5 5 4 5 7 5 4 6 5 5 7 5 4 6 4 5 6 4 5 6 5 5 7 4 5 4 4 5 6 4 6 5 6 6
75745676546556655645676446565466557546675764
47565566567675764765556
These are the number of successes in each of the 100 experiments. For instance, in
the first experiment, we got 5 heads, in the second experiment, we got 6 heads, and
so on.
Conclusion:
[Link] binomial distribution is an essential statistical concept that provides insights
into the probability of a certain number of successes in a given number of
independent trials. Its applications are wide and varied, spanning numerous fields
from biology to finance.
2.R programming language has several functions for performing operations related
to the binomial distribution, such as dbinom(), pbinom(), qbinom(), and rbinom(),
each serving its unique purpose.
16 | P a g e
[Link]() function gives the cumulative probability of a specified or fewer
number of successes, while qbinom() helps to find the quantile, or the number of
successes at a given percentile.
[Link] rbinom() function is an effective tool for generating random numbers that
follow a binomial distribution, which can be particularly useful in scenarios like
simulations or data analysis involving bootstrapping.
Poisson Distribution
The Poisson distribution represents the probability of a provided number of cases
happening in a set period of space or time if these cases happen with an identified
constant mean rate (free of the period since the ultimate event). Poisson
distribution has been named after Siméon Denis Poisson(French Mathematician).
• dpois()
• ppois()
• qpois()
17 | P a g e
• rpois()
dpois ()
The dpois function finds the probability that a certain number of successes occur
based on an average rate of success, using the following syntax:
dpois(x, lambda)
where:
• x: number of successes
• lambda: average rate of success
18 | P a g e
It is known that a certain website makes 10 sales per hour. In a given hour, what is
the probability that the site makes exactly 8 sales?
dpois(x=8, lambda=10)
#0.112599
ppois()
The ppois function finds the probability that a certain number of successes or less
occur based on an average rate of success, using the following syntax:
ppois(q, lambda)
where:
• q: number of successes
• lambda: average rate of success
Here’s are a couple examples of when you might use this function in practice:
It is known that a certain website makes 10 sales per hour. In a given hour, what is
the probability that the site makes 8 sales or less?
ppois(q=8, lambda=10)
#0.3328197
The probability that the site makes 8 sales or less in a given hour is 0.3328197.
It is known that a certain website makes 10 sales per hour. In a given hour, what is
the probability that the site makes more than 8 sales?
ppois(q=8, lambda=10)
#0.6671803
The probability that the site makes more than 8 sales in a given hour is 0.6671803.
19 | P a g e
qpois()
The qpois function finds the number of successes that corresponds to a certain
percentile based on an average rate of success, using the following syntax:
qpois(p, lambda)
where:
• p: percentile
• lambda: average rate of success
It is known that a certain website makes 10 sales per hour. How many sales would
the site need to make to be at the 90th percentile for sales in an hour?
qpois(p=.90, lambda=10)
#14
A site would need to make 14 sales to be at the 90th percentile for number of sales
in an hour.
rpois()
The rpois function generates a list of random variables that follow a Poisson
distribution with a certain average rate of success, using the following syntax:
rpois(n, lambda)
where:
20 | P a g e
Generate a list of 15 random variables that follow a Poisson distribution with a rate
of success equal to 10.
Since these numbers are generated randomly, the rpois() function will produce
different numbers each time. If you want to create a reproducible example, be sure
to use the [Link]() command.
x= [Link][(3,5,7,9],p=[0.1,0.3,0.6,0.0],size=(10))
print(x)
Output : 5 7 3 5 7 7 5 7 7 5
In this function we are use another module to visualise random distribution graphically. i.e
Seaborn module
● Uniform distribution
● Normal distribution
● Student -t distribution
● Chi-square distribution
[Link] distribution: It is one of the common probability density functions where every
event has equal chances of occurring.
21 | P a g e
Eg: Generation of random numbers.
It has 3 parameters:
[Link] distribution:
It is one of the most important distribution.
It is also called as the Gaussian distribution after the German Mathematician Carl Friedrich
Gauss. It fits the probability distribution of many events
student t-Distribution
The student's t-distribution is similar to a normal distribution and used in
statistical inference to adjust for uncertainty.
Or
22 | P a g e
Student t-Distribution is a probability distribution that is used to calculate
population parameters when the sample size is small and when the
population variance is unknown.
23 | P a g e
If the sample is small, the t-distribution is wider. If the sample is big,
the t-distribution is narrower.
The bigger the sample size is, the closer the t-distribution gets to the
standard normal distribution.
T distribution
The green curve has the smallest sample [Link] the t-distribution this is
expressed as 'degrees of freedom' (df), which is calculated by subtracting 1 from
the sample size (n).
For example a sample size of 30 will make 29 degrees of freedom for the t-
distribution.
The t-distribution is used to find critical t-values and p-values (probabilities) for
estimation and hypothesis testing.
24 | P a g e
Example for finding t-values and p-values
Find the t-values of a p-value by using a t-table or with programming.
Ex:program
print([Link](0.75, 29))
Result :
0.6830438592467808
Ex:program
print([Link](2.1, 29))
25 | P a g e
Result :
0.9777290209818548
26 | P a g e
27 | P a g e
Chapter-4
Statistical Testing and Modelling
Statistical testing:-
• It involves using functions and packages to perform hypothesis test analyse data and raw conclusion
based on statistical significance.
Example:
g1<-rnorm(30,mean=50,sd=10)
g2<- rnorm(30,mean=55,sd=12)
t_test_result<- [Link](g1,g2)
print(t_test_result)
These tests assume that the data follows a specific distribution (e.g., normal distribution). t-test:
Compares means of two groups to determine if they are significantly different.
ANOVA (Analysis of Variance): Tests the differences among means of three or more groups.
Pearson correlation: Measures the strength and direction of the linear relationship between two
continuous variables.
28 | P a g e
Here's an example:
print(t_result)
This code performs a two-sample t-test comparing group1 and group2 and displays the test results,
including the t-statistic, degrees of freedom, and p-value.
Non-Parametric Tests:
These tests are distribution-free and don’t require assumptions about the data distribution
Kruskal-Wallis test: Compares medians of three or more independent groups. Spearman correlation:
Assesses the strength and direction of monotonic association between variables.
Here's an example:
print(wilcox_result)
This code performs a Wilcoxon signed-rank test comparing the before and after data and displays the
test results, including the test statistic, the p-value, and information about the alternative hypothesis.
Chi-Square Tests:
29 | P a g e
Chi-Square test of independence: Examines whether there's a significant association between
categorical variables in a contingency table.
Chi-Square goodness of fit test: Determines if the observed categorical data matches the expected
Distribution.
Correlation test:
To measure relationship between 2 variables
Example:
data(mtcars)
model<-lm(mpg~wt,data=mtcars)
summary(model)
30 | P a g e
Statistical testing and modelling in R offer several advantages.
• R provides a vast array of statistical packages and libraries, making it versatile for various
analyses. Its advantages include:
• Comprehensive Statistical Tools: R offers a wide range of statistical tests and modelling
techniques, allowing users to conduct complex analyses, regression, ANOVA, etc.
• Graphical Capabilities: R has powerful visualization libraries like ggplot2, allowing users to
create detailed, customizable plots and graphs to better understand data distributions and
relationships.
• Community Support: Being an open-source language, R has a large and active community.
Users can access numerous resources, forums, and packages shared by statisticians and data
scientists.
• Reproducibility: R scripts enable the reproduction of analyses. Others can replicate your work,
enhancing transparency and credibility.
• Integration and Compatibility: R easily integrates with other languages, databases, and
platforms. It can interact with various data sources, enhancing its flexibility. VII. Free and
Open Source: R is free to use, making it accessible to researchers, students, and professionals
regardless of budget constraints.
• These advantages make R a preferred choice for statistical analysis and modelling in many
fields.
Sampling distribution
31 | P a g e
Sampling distribution refers to the distribution of sample statistic. Like the mean Or standard
deviation, computed from multiple samples of the same size taken from a population.
Example:-
data(iris)
head(iris)
[Link](123)
i) Statistical Inference: They allow you to perform various statistical inferences, such as
estimating parameters, constructing confidence intervals, and conducting hypothesis tests
based on samples.
ii) Simulation Studies: Sampling distributions in R enable the simulation of various scenarios,
helping researchers understand the behavior of statistics under different conditions.
iii) Visualizations: R provides robust tools for visualizing sampling distributions, allowing for clear
and intuitive representations that aid in understanding the underlying statistical concepts.
iv) Analyzing Sampling Variability: It helps in understanding the variability inherent in samples,
crucial for making generalizations about populations based on sample data.
v) Modeling and Analysis: R facilitates the creation and analysis of complex statistical models,
allowing for a deeper exploration of sampling distributions and their implications in real-
world applications.
32 | P a g e
Some disadvantages include:
I. Assumptions: They often assume the data comes from a particular distribution, and if this
assumption is violated, the results may be inaccurate.
II. Sample Size: Small sample sizes might not accurately represent the population, leading to
biased estimates
III. Complexity: Some sampling methods might be complex to implement or understand,
especially for beginners.
IV. Representativeness: If the sampling method used isn't random or representative, it might not
reflect the true characteristics of the population.
V. Interpretation: Sometimes interpreting the results from sampling distributions can be
challenging, especially when dealing with complex statistical models or parameters.
HYPOTHESIS TESTING
➢ A hypothesis is a claim about a population parameter.
"The average height of people in Denmark is more than 170 cm." In this case, the parameter is the
average height of people in Denmark (µ). The null and alternative hypothesis would be:
Alternative hypothesis: The average height of people in Denmark is more than 170 cm. The claims are
often expressed with symbols like this: H0:µ=170cm H1:µ>170cm If the data supports the alternative
33 | P a g e
hypothesis, we reject the null hypothesis and accept the alternative hypothesis. If the data does not
support the alternative hypothesis, we keep the null hypothesis.
The significance level is a percentage probability of accidentally making the wrong conclusion.
• α=0.1(10%)
• α= 0.05 (5%)
• α=0.01 (1%)
A lower significance level means that the evidence in the data needs to be stronger to reject the null
hypothesis.
There is no "correct" significance level - it only states the uncertainty of the conclusion.
The type of probability distribution depends on the type of test. Common examples are:
• The critical value approach compares the test statistic with the critical value of the significance level.
• The p-value approach compares the p-value of the test statistic and with the significance level.
34 | P a g e
The rejection region is an area of probability in the tails of the distribution.
The size of the rejection region is decided by the significance level (α).
The value that separates the rejection region from the rest is called the critical value.
If the test statistic is inside this rejection region, the null hypothesis is rejected.
For example, if the test statistic is 2.3 and the critical value is 2 for a significance level (α=0.05):
The p-value of the test statistic is the area of probability in the tails of the distribution from the value of
the test statistic.
If the p-value is smaller than the significance level, the null hypothesis is rejected.
The p-value directly tells us the lowest significance level where we can reject the null hypothesis.
5. Conclusion
One condition is that the sample is randomly selected from the population.
The other conditions depends on what type of parameter you are testing the hypothesis for.
35 | P a g e
Common parameters to test hypotheses are:
Testing means
Hypothesis testing in R,A formal statistical test called a hypothesis test is used to confirm or Disprove a
statistical hypothesis.
5. Conclusion
1. Checking the Conditions The conditions for calculating a confidence interval for
a proportion are:
• The sample is randomly selected
• And either
In the example, the sample size was 30 and it was randomly selected, so the conditions are fulfilled.
"The average age of Nobel Prize winners when they received the prize is more than 55"
In this case, the parameter is the mean age of Nobel Prize winners when they received the prize
(u)
The null and alternative hypothesis are then:
Null hypothesis: The average age was 55.
Alternative hypothesis: The average age was more than 55.
Which can be expressed with symbols as:
𝐻0 : 𝜇 = 55
𝐻1 : 𝜇 > 55
36 | P a g e
This is a 'right tailed' test, because the alternative hypothesis claims that the proportion is more
than in the null hypothesis.
3. Deciding the Significance Level
The significance level (𝛼) is the uncertainty we accept when rejecting the null hypothesis in a
hypothesis test.
The significance level is a percentage probability of accidentally making the wrong conclusion.
▪ 𝛼 = 0.1(10%)
▪ 𝛼 = 0.5(5%)
▪ 𝛼 = 0.01(1%)
A lower significance level means that the evidence in the data needs to be stronger to reject the null
hypothesis.
There is no "correct" significance level - it only states the uncertainty of the conclusion.
The formula for the test statistic (TS) of a population mean is: 𝑥 − 𝜇 𝑠 ⋅ √𝑛
𝑥 − 𝜇 is the difference between the sam3ple mean (𝑥) and the claimed population mean (𝜇 ).
The sample mean (𝑥) was 62.1 The sample standard deviation (𝑠) was 13.46
Example
With R use built-in math and statistics functions to calculate the test statistic.?.
37 | P a g e
# Specify the sample mean (x_bar), the sample standard deviation (s), the mean claimed in the null-
hypothesis (mu_null), and the sample size (n)
s <- 13.46
mu_null <- 55 n <- 30
output 2.8891754519217536
[Link]
• The critical value approach compares the test statistic with the critical value of the
significance level
• The P-value approach compares the P-value of the test statistic and with the significance
level.
Proportion
A population proportion is the share of a population that belongs to a particular category
Hypothesis tests are used to check a claim about the size of that population proportion.
38 | P a g e
• Not being in the category
In our example, we randomly selected 10 people that were born in the US.
The rest were not born in the US, so there are 30 in the other category.
In this case, the parameter is the mean age of Nobel Prize winners when they received the prize (u)
𝐻0 : 𝜇 = 55
𝐻1 : 𝜇 > 55
This is a 'right tailed' test, because the alternative hypothesis claims that the proportion is more than in
the null hypothesis.
The significance level is a percentage probability of accidentally making the wrong conclusion.
𝛼 = 0.1(10%)
𝛼 = 0.5(5%)
𝛼 = 0.01(1%)
39 | P a g e
A lower significance level means that the evidence in the data needs to be stronger to reject the null
hypothesis.
There is no "correct" significance level - it only states the uncertainty of the conclusion.
The formula for the test statistic (TS) of a population mean is:
𝑥 − 𝜇 𝑠 ⋅ √𝑛
𝑥 − 𝜇 is the difference between the sam3ple mean (𝑥) and the claimed population mean (𝜇 ).
0.25− 0.20 √0.2(1 −0.2) ⋅ √40 = 0.05 √0.2(0.8) ⋅ √40 = 0.05 √0.16 ⋅ √40 ≈ 0.05 0.4 ⋅ 6.325 = 0.791 ―
You can also calculate the test statistic using programming language functions:
Example
With R use the built-in [Link]() function to calculate the test statistic for a proportion.
# Specify the sample occurrences (x), the sample size (n), and the null-hypothesis claim (p)
x <- 10
n <- 40
p <- 0.20
p_hat = x/n
40 | P a g e
(p_hat-p)/(sqrt((p*(1-p))/(n)
Output
0.7905694150420945
5. Concluding
There are two main approaches for making the conclusion of a hypothesis test:
• The critical value approach compares the test statistic with the critical value of the
significance level.
• The P-value approach compares the P-value of the test statistic and with the significance
level.
Categorical Variables
Categorical variables in R are stored into a factor. Let’s check the code below to convert a character
variable into a factor variable in R. Characters are not supported in machine learning algorithm, and
the only way is to convert a string to an integer.
Syntax
Arguments:
• not decimal.
• Levels: A vector of possible values taken by x. This argument is optional. The default value is
the unique list of items of the vector x.
• Labels: Add a label to the x categorical data in R. For example, 1 can take x: A vector of
categorical data in R. Need to be a string or integer, the label `male` while 0, the label
`female`.
• ordered: Determine if the levels should be ordered in categorical data in R.
Example
• Race
• Age group
• Educational level
41 | P a g e
Error
Defination:
errors typically occur when the code you're trying to run can't be executed due to some reasons.
We have not yet discussed the fact that we are not guaranteed to make the correct decision by this
process of hypothesis testing. Maybe you are beginning to see that there is always some level of
uncertainty in statistics.
Let’s think about what we know already and define the possible errors we can make in hypothesis
testing. When we conduct a hypothesis test, we choose one of two possible conclusions based upon our
data.
If the p-value is smaller than your pre-specified significance level (α, alpha), you reject the null
hypothesis and either
You have made the correct decision since the null hypothesis is false
OR
You have made an error (Type I) and rejected Ho when in fact Ho is true (your data happened to be a
RARE EVENT under Ho)
If the p-value is greater than (or equal to) your chosen significance level (α, alpha), you fail to reject the
null hypothesis and either
You have made the correct decision since the null hypothesis is true
OR
You have made an error (Type II) and failed to reject Ho when in fact Ho is false (the alternative
hypothesis, Ha, is true)
The following summarizes the four possible results which can be obtained from a hypothesis test. Notice
the rows represent the decision made in the hypothesis test and the columns represent the (usually
unknown) truth in reality.
mod12-errors1
42 | P a g e
Although the truth is unknown in practice – or we would not be conducting the test – we know it must
be the case that either the null hypothesis is true or the null hypothesis is false. It is also the case that
either decision we make in a hypothesis test can result in an incorrect conclusion!
A TYPE I Error occurs when we Reject Ho when, in fact, Ho is True. In this case, we mistakenly reject a
true null hypothesis.
A TYPE II Error occurs when we fail to Reject Ho when, in fact, Ho is False. In this case we fail to reject a
false null hypothesis.
When our significance level is 5%, we are saying that we will allow ourselves to make a Type I error less
than 5% of the time. In the long run, if we repeat the process, 5% of the time we will find a p-value <
0.05 when in fact the null hypothesis was true.
In this case, our data represent a rare occurrence which is unlikely to happen but is still possible. For
example, suppose we toss a coin 10 times and obtain 10 heads, this is unlikely for a fair coin but not
impossible. We might conclude the coin is unfair when in fact we simply saw a very rare event for this
fair coin
Power
Defination
Power is the probability of avoiding a Type II error. The higher the statistical power of a test, the lower
the risk of making a Type II error.
Power is usually set at 80%. This means that if there are true effects to be found in 100 different studies
with 80% power, only 80 out of 100 statistical tests will actually detect them.
It is often the case that we truly wish to prove the alternative hypothesis. It is reasonable that we would
be interested in the probability of correctly rejecting the null hypothesis. In other words, the probability
of rejecting the null hypothesis, when in fact the null hypothesis is false. This can also be thought of as
the probability of being able to detect a (pre-specified) difference of interest to the researcher.
43 | P a g e
Assume that the null hypothesis is false for a given hypothesis test. All else being equal, we
have the following:
• Larger samples result in a greater chance to reject the null hypothesis which means an increase
in the power of the hypothesis test.
• If the effect size is larger, it will become easier for us to detect. This results in a greater chance
to reject the null hypothesis which means an increase in the power of the hypothesis test. The
effect size varies for each test and is usually closely related to the difference between the
hypothesized value and the true value of the parameter under study.
• From the relationship between the probability of a Type I and a Type II error (as α (alpha)
decreases, β (beta) increases), we can see that as α (alpha) decreases, Power = 1 – β = 1 – beta
also decreases.
• There are other mathematical ways to change the power of a hypothesis test, such as changing
the population standard deviation; however, these are not quantities that we can usually
control so we will not discuss them here.
Analysis of variance
ANOVA tests whether there is a difference in means of the groups at each level of the
independent variable. The null hypothesis (H0) of the ANOVA is no difference in means, and the
alternative hypothesis (Ha) is that the means are different from one another.
The standard R anova function calculates sequential ("type-I") tests. These rarely test interesting
hypotheses in unbalanced designs. A MANOVA for a multivariate linear model (i.e., an object of
class "mlm" or "manova" ) can optionally include an intra-subject repeated-measures design.
Introduction to ANOVA in R
ANOVA in R is a mechanism facilitated by R programming to carry out the
that allows the user to check if the mean of a particular metric across a various
population is equal or not, through the formulation of the null and alternative
44 | P a g e
Why ANOVA?
• This technique is used to answer the hypothesis while analyzing multiple groups
researchers with the result of the hypothesis. In order to get accurate results,
sample means, sample size, and standard deviation from each individual group
• It is possible to observe the mean individually for each of the three groups for
comparison. However, this approach has limitations and may prove incorrect
because these three comparisons don’t consider total data and thus may lead to
type 1 error. R provides us with the function to conduct the ANOVA analysis to
examine variability among the independent groups of data. There are five stages
of conducting the ANOVA analysis. In the first stage, data is arranged in csv
format, and the column is generated for each variable. One of the columns would
second stage, the data is read in R studio and named appropriately. In the third
Finally, the ANOVA in R is defined and analyzed. In the below sections, I’ve
45 | P a g e
provided a couple of case study examples in which ANOVA techniques should be
used.
• Six insecticides were tested on 12 fields each, and the researchers counted the
number of bugs that remained in each field. Now the farmers need to know if the
insecticides make any difference and which one they best use. You answer this
once per day (1 time), 10mg twice per day (2 times) 5 mg four times per day (4
times). The two remaining conditions (drugD and drugE) represented competing
(response)?
Example program:
[Link]('multcomp')
library(multcomp)
str(cholesterol)
attach(cholesterol)
aov_model <- aov(response ~ trt)
46 | P a g e
chapter -5
linear regression :
it is the basic and commonly used type for predictive [Link] is a statistical
approach for modeling and relationship betweena dependent variable and a given
set of independent variables
Advantages Disadvantages
47 | P a g e
Simple regression
The simple linear regression is used to predict a quantitative outcome y on the basis of
one single predictor variable x . The goal is to build a mathematical model (or formula)
that defines y as a function of the x variable.
Advantage
➢ It is easy to interpret: The slope and y-intercept of the regression line can be easily
understood and used to make predictions.
➢ It requires a small amount of data: Simple linear regression can be used with a small
number of observations.
➢ It is computationally efficient: Simple linear regression can be calculated using basic
algebra, making it easy to implement and run.
➢ It is a good starting point: Simple linear regression can be used as a starting point
for more complex models and can help identify trends in the data.
➢ It is relatively robust to outliers: Simple linear regression is relatively robust to the
presence of outliers in the data.
➢ It can handle non-linear relationship by using non-linear transformation of
predictors.
➢ It's good for understanding the relationship between a single independent variable
and a single dependent variable
(or)
It is an extension of simple linear regression used to predict an outcome variable Y on the basis of
multiple distinct predictor variable X.
y=a+b1x1+b2x2+bn
48 | P a g e
EXAMPLE: selling price of the a house can depend on the desirability of the location,number of
rooms,the year the house was built,the square footage of the lot and number of other factors.
Real-life applications:
For ex you can a model that predicts productivity based on variables such as
education,experience,skills,motivation,feedback and incentives.
■ Health outcomes: used to investigate the Influence of various factors on health outcomes,such as
blood pressure,cholestero,diabetes.
Advantages
➢ It has the ability to determine the relative influence of one or more predictor variables to the
critierion value.
➢ It also has the ability to identify outliers or anomalies.
Disadvantage
It need high level mathematics to analyze the data and is required in the statistical program.
It is difficult for researchers to interpret the resultsof the multiple regression analysis on the basis
ofassumptions as it has a requirementof a large sample odata to get the effective result.
■ Example program
Consider the data set “mtcars” avilable in the R environment .it gives a comparision between different
car models in terms of mileage per gallon(mpg),cylinder displacement(disp),hose power(hp),weight of
the car(wt) and some more parameters.
Print(head(input))
49 | P a g e
Hornet 4 Drive 21.4 258 110 3.215
Running a regression model with many variables including irrelevant ones will lead to a
needlessly complex model. Stepwise regression is a way of selecting important variables to get a
simple and easily interpretable model.
Below we discuss how forward and backward stepwise selection work, their advantages, and
limitations and how to deal with them.
Forward stepwise
Forward stepwise selection (or forward selection) is a variable selection method which:
o Begins with a model that contains no variables (called the Null Model)
o Then starts adding the most significant variables one after the other
o Until a pre-specified stopping rule is reached or until all the variables under
consideration are included in the model
[Link] the most significant variable to add at each stepThe most significant variable can
be chosen so that, when added to the model:
The stopping rule is satisfied when all remaining variables to consider have a p-value larger
than some specified threshold, if added to the [Link] we reach this state, forward
50 | P a g e
selection will terminate and return a model that only contains variables with p-values <
threshold threshold.
forward$anova
forward$coefficients
Backward stepwise
Backward stepwise selection (or backward elimination) is a variable selection method which:
o Begins with a model that contains all variables under consideration (called the
Full Model)
o Then starts removing the least significant variables one after the other
o Until a pre-specified stopping rule is reached or until no variable is left in the
model
• Its elimination from the model causes the lowest increase in RSS (Residuals Sum of
Squares) compared to other predictors
51 | P a g e
2. Choose a stopping rule
The stopping rule is satisfied when all remaining variables in the model have a p-value smaller
than some pre-specified [Link] we reach this state, backward elimination will
terminate and return the current step’s model.
backward$anova
backward$coefficient
Certainly, let’s delve into diagnostic procedures for linear regression in R. We’ll focus on the key
diagnostic checks:
Outlier Detection: Identify potential outliers. Influence and Cook’s Distance: Identify influential
observations.
52 | P a g e
Multicollinearity: Check for high correlation between predictors.
Let’s provide R code examples for each of these diagnostics using a hypothetical dataset.
# Create diagnostic plots (residuals vs. fitted values, residuals vs. normal quantiles,
plot(model)
Advanced graphics
R also has a higher-level set of graphics functions which make it possible to produce
complex graphics with a single function call. The high level function which produces
graphs is called plot.R Programming. R includes at least three graphical systems, the
standard graphics package, the lattice package for Trellis graphs and the grammar-of-
graphics ggplot2 package. R has good graphical capabilities but there are some
alternatives like gnuplot. R Programming.
➢ Box Plotting
➢ Histograms
➢ Bar Plotting
➢ Scatter Plot
53 | P a g e
The R programming graphics available to make up the image
• ➢ Plot region
• ➢ Figure region
• ➢ Outer region
The number lines of text that can fit on top of one another parallel to each edge. We can specify these
as vectors of length 4 in a particular order; each of the four elements corresponds to one of the four
sides; c(bottom, left, top, right).
About margins
Margins are the the index number representing either the row (1) or the column (2)
OR
All the plots in R have margins surrounding them that separate the main plotting space from the area
where the axes, labels and addition text lie
The graphical parameters oma (outer margin) and mar (figure margin) are used to control these
amounts; like mfrow, they are initialized through a call to par before you begin to draw any new plot.
R> par()$oma
[output] 0 0 0 0
R> par()$mar
54 | P a g e
➢ Plot Region:-
The plot region is all you’ve dealt with so far. This is where your actual plot appears and where you’ll
usually be drawing your points, lines, text, and so on. The plot region uses the user coordinate system,
which reflects the value and scale of the horizontal and vertical axes.
Example:-
y <- x^2
output:-
55 | P a g e
➢ Figure Region:-
The figure region is the area that contains the space for your axes, their labels, and any titles. These
spaces are also referred to as the figure margins.
Example:-
plot(1, type = "n", xlab = "", ylab = "", xlim = c(0, 10), ylim = c(0, 5))
# Add a title
title(“Figure Region in R)
Output:-
➢ Outer Region:-
The outer region, also referred to as the outer margins, is additional space around the figure region that
is not included by default but can be specified if it’s needed.
56 | P a g e
# Example of Outer Product in R
for (i in 1:nrow(outer_region)) {
for (j in 1:ncol(outer_region)) {
cat("Processing element at (", i, ", ", j, "): ", outer_region[i, j], "\n", sep = "")
# Example matrix
iterate_outer_region(example_matrix)
x <- 1:10
y <- c(3, 5, 2, 8, 7, 4, 6, 9, 1, 3)
(x, y, pch = 16, main = "Scatter Plot with Margins", xlab = "X-axis", ylab = "Y-axis")
57 | P a g e
# Define margins (you can modify these values according to your data)
margin_left <- 3
margin_right <- 7
margin_bottom <- 2
margin_top <- 8
mtext
58 | P a g e
R Program to illustrate plotting and margin ?
# Sample data
x <- 1:10
y <- c(3, 5, 2, 8, 7, 4, 6, 9, 1, 3)
plot(x, y, pch = 16, main = "Scatter Plot with Margins", xlab = "X-axis", ylab = "Y-axis")
# Define margins (you can modify these values according to your data)
margin_left <- 3
margin_right <- 7
margin_bottom <- 2
margin_top <- 8
Output:-
59 | P a g e
R program using figure margins and outer margins.
We are used the ‘par()’ function to set both figure margins (‘mar’) and outer margins (‘oma’)
Example:-
60 | P a g e
# Reset par settings to default
In the given example we are used both figure margin and outer margin.
mtext()
In R, the ‘mtext()’ function is used to add text to the margins of a plot. It stands for “Margin Text” and is
commonly used to label the axes, add titles, or provide additional annotations to a plot. The ‘mtext()’
function allows you to specify the text, side (which margin to place the text on), line , and other
parameters for customizing the appearance of the text.
Example program:-
mtext("Rotated Text", side = 1, line = 2, col = "brown", adj = 0, padj = 0.5, srt = 90)
61 | P a g e
Output:-
In this example, ‘mtext(“X-axis label”, side = 1,line =3)’ adds the text “X-axis label” to the bottom
margin(side=1) at line 3. Similarly, ‘mtext(“Y-axis label”, side = 2, line = 3)’ adds the text “Y-axis label” to
the left margin (side = 2) at line 3.
We can customize the appearance of the text further by using additional parameters, such as ‘col’ for
color, ‘cex’ for text size, and ‘font’ for text font. The ‘mtext()’ function provides flexiblility in annotating
and enhancing the visual presentation of plots in R.
62 | P a g e
Co-ordinate:
Typically refers to a pair of values that represent a point in a multi-dimension space.
Or
The co-ordinate like (x,y) they are the numeric value representing position along respective area.
Application
Finance and stack market analysis: helps traders to gain on insight into economy stack
market
Advantages:
Disadvantages:
• Limited flexibility
• Limited scripiting visibility
• Security
63 | P a g e
Program
Plot(1,type=”n”,xlab=”x”,ylab=”y”,main=”point_and_click interaction”)
Points<-locator()
Else
The method is described in the Embedding base graphics plots in grid viewports section of the
gridBase vignette.
The gridBase package contains functions to set sensible parameters for the plotting region of
the base plot. So we need these packages
R plot: The plot() function is used to draw points (markers) in a diagram. The function takes
parameters for specifying points in the diagram. Parameter 1 specifies points on the x-axis.
Parameter 2 specifies points on the y-axis.
64 | P a g e
• Types of traditional R plot
These include density plots (histograms and kernel density plots), dot plots, bar charts (simple,
stacked, grouped), line charts, pie charts (simple, annotated, 3D), boxplots (simple, notched,
violin plots, bagplots) and Scatterplots (simple, with fit lines, scatterplot matrices, high density
plots, and 3D plots).
Scatterplots: A “scatter plot” is a type of plot used to display the relationship between two
numerical variables, and plots one dot for each observation.
Line chart:
A line chart is a graph that connects a series of points by drawing line segments between them. These
points are ordered in one of their coordinate (usually the x-coordinate) value. Line charts are usually
used in identifying the trends in data. The plot() function in R is used to create the line graph.
Bar chart:
A bar chart or bar graph is a chart or graph that presents categorical data with rectangular bars with
heights or lengths proportional to the values that they represent. The bars can be plotted vertically or
horizontally. A vertical bar chart is sometimes called a column chart.
66 | P a g e
Specialized text and label notation.
Font: -
67 | P a g e
• Integer selector for controlling bold and italic typeface
Greek symbols: -
Mathematical expression:
Recall the notation that R stands for the real numbers. Similarly, R2 is a two-dimensional vector, and R3 is
a three-dimensional vector.
Real numbers.
68 | P a g e
• Simple Math. In R, you can use operators to perform common mathematical operations on
numbers. .
• Built-in Math Functions. R also has many built-in math functions that allows you to perform
mathematical tasks on numbers.
• sqrt() The sqrt() function returns the square root of a number
• abs()
• ceiling() and floor()
Defining Colors
A colour palette is a combination of colours used in UI designs when designing and interface when used
correctly colours platform from a visual foundation of your brand help to maintain the consistency and
to make your user interface aesthetically pleasing and enjoyable to use.
Colour symbolism art , color in a computer programs are represented by combining 3 “pigments”, color
can be specified by col keyword
HEX Value:-
Where rr (red), gg (green) and bb (blue) are hexadecimal values between 00 and ff (same as decimal 0-
255). For example, #ff0000 is displayed as red, because red is set to its highest value (ff) and the others
are set to the lowest value (00). To display black, set all values to 00, like this: #000000.
Hex color codes start with a pound sign or hashtag (#) and are followed by six letters and/or numbers.
The first two letters/numbers refer to red, the next two refer to green, and the last two refer to blue.
The color values are defined in values between 00 and FF (instead of from 0 to 255 in RGB). # We need
this line of code to show graphs in our compiler bitmap(file="[Link]") plot(1:10, col="red")
69 | P a g e
Plot() :-
The plot() function is used to draw points (markers) in a diagram. The function takes parameters for
specifying points in the diagram. Parameter 1 specifies points on the x-axis. Parameter 2 specifies points
on the y-axis.
Example:-
Dimensions :-
Dimensions are represented by dim() function a dimension statement defines the array and sets up
the number of elements within the dimensions.
The dim function of the R programming language returns the dimension (e.g. the number of columns
and rows) of a matrix, array or data frame. Above, you can see the R code for the application of dim in R.
70 | P a g e
Plotting in higher dimensions by representing and
using colors
High-dimensional data are defined as data in which the number of features
(variables observed), p, are close to or larger than the number of observations (or data points), n. The
opposite is low-dimensional data in which the number of observations, n, far outnumbers the number of
features.
HIGHER DIMENSIONS :-
A dimensions beyond the three dimensions of space that we experience in our everyday lives. Higher
dimensions typically refer to array or matrices with more then two dimensions.
We can also work higher dimensions data using functions like array() to create and manipulate the
structures. Example 1:- 3D dimension scatterplot library(scatterplot3d) [Link](42) num_points<-100
x<-runif(num_points) y<-runif(num_points) z<-runif(num_points) w<-runif(num_points)
color_palette<-colorRampPalette(c("pink","black","red","orange")) colors<-
color_palette(100)[cut(w,100)]
scatterplot3d(x ,y , z, color=colors, main="3D scatterplot with color mapping") Output:-
71 | P a g e
Example 2:- 2D dimensions scatterplot
72 | P a g e
3D Scatter plot
2 marks questions.
73 | P a g e
• Points3d(): to add points or lines into existing plot.
• Plane3d(): to ass a plane into the existing plot.
• Box3d(): to add or refresh a box around the plot.
9. Specifying the legend position using keywords.
• Bty=”n”: to remove the box around the legend .
• Bg=”transparent”: to change the background colour of the legend box to transparent
colour.
• Inset: to modify the distance (s) between plot margins and the legend box.
• Horiz: a logical value; if TRUE, set the legend horizontally rather than vertically.
• Xpd: a logical values; if enables the legend items to be drawn outside the plot.
10. Write the regression plane and supplementary points functions.
• The result of scatterplot3d () is assigned to s3d.
• A linear model is calculated as follow:ln(zvar~xvar+yvar)
• Assumption:zvar depends on xvar and yvar.
• The function s3d$plane3d() is used to add the regression plane.
• Supplementary points are added using the function s3d$points3d().
11. Write the example program for 3d Scatterplot.
#install and load the required package
[Link](“scatterplot3d”)
Library (scatterplot3d)
X<-rnorm(100)
Y<-rnorm(100)
Z<-rnorm(100)
Scatter3d(x,y,z,main=”3d Scatterplot”,pch=19,color=”blue”,xlab=”Xaxis”,ylab=”Y-axis”,zlab=”Z-
axis”)
74 | P a g e
ylab=”sepal width(cm)”, zlab=”petal
length (cm)”)
13. Change the points shapes in group.
shapes = c(16, 17, 18)
75 | P a g e