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

Hypothesis Testing Techniques in R

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

Hypothesis Testing Techniques in R

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

Hypothesis Testing using R

🔹 1. What is Hypothesis Testing?


 Hypothesis testing is a statistical method used to make decisions about population
parameters based on sample data.
 It checks whether the observed results are due to chance or represent true
differences.

👉 In R, hypothesis testing is straightforward because of built-in functions like [Link](),


[Link](), [Link](), and aov().

🔹 2. Steps in Hypothesis Testing


1. State the hypotheses
o Null Hypothesis (H₀): No effect / no difference.
o Alternative Hypothesis (H₁): There is an effect / difference.
2. Choose significance level (α)
o Commonly 0.05 (5%).
3. Compute test statistic (t, χ², F, etc.).
4. Find the p-value.
5. Make a decision:
o If p < α → Reject H₀.
o If p ≥ α → Fail to reject H₀.

Types of Hypothesis Testing in R:

One-Sample T-Test – compares sample mean with population mean.


Independent Two-Sample T-Test – compares means of two independent groups.
Paired T-Test – compares means of same group before and after.
Chi-Square Test – tests independence/association between categorical variables.
Correlation Test – tests correlation between two continuous variables (Pearson /
Spearman).
ANOVA (Analysis of Variance) – compares means of 3 or more groups.
Regression-based Tests – tests significance of predictors in regression models.

T-Test
🔹 What is a T-Test?

 A t-test is a statistical test used to determine if the mean of a dataset significantly


differs from a known value or from another group.
 It is based on the Student’s t-distribution.
 Especially useful for small sample sizes (n < 30) where the population standard
deviation is unknown.

🔹 Why do we use a T-Test?

 To check if differences in means are due to random chance or are statistically


significant.
 Helps in decision-making: e.g., “Is a new medicine effective?” or “Do two teaching
methods give the same average performance?”

🔹 When to use T-Test?

 Data is continuous (numerical).


 Data is approximately normally distributed.
 For small or moderate sample sizes.
 When comparing means of one sample vs population mean, two independent
samples, or paired samples.

🔹 Steps in Hypothesis Testing with T-Test

1. State hypotheses:
o Null hypothesis (H0H_0H0): no difference in means.
o Alternative hypothesis (H1H_1H1): difference exists.
2. Choose significance level (α): commonly 0.05.
3. Compute test statistic (t-value).
4. Find p-value using t-distribution.
5. Decision:
o If p < α → Reject H0H_0H0 → difference is significant.
o If p ≥ α → Fail to reject H0H_0H0.

🔹 R Programs & Examples

(a) One-sample T-Test

# Example: Average marks


marks <- c(45, 52, 47, 49, 51, 53, 48)
[Link](marks, mu = 50)

Sample Output:

One Sample t-test


t = -0.577, df = 6, p-value = 0.586

Interpretation: Since p > 0.05, the sample mean is not significantly different from 50.

(b) Independent Two-sample T-Test

# Example: Compare teaching methods


method1 <- c(70, 75, 80, 72, 78)
method2 <- c(65, 68, 74, 70, 69)
[Link](method1, method2, [Link] = TRUE)

Sample Output:

Two Sample t-test


t = 2.24, df = 8, p-value = 0.055

Interpretation: Since p ≈ 0.055 > 0.05, no strong evidence of difference, but result is close
to significant.

(c) Paired T-Test

# Example: BP before vs after treatment


before <- c(120, 122, 119, 130, 128)
after <- c(115, 118, 116, 124, 122)
[Link](before, after, paired = TRUE)

Sample Output:

Paired t-test
t = 5.67, df = 4, p-value = 0.005

Interpretation: Since p < 0.05, treatment significantly reduced blood pressure.

🔹 Pros and Cons of T-Test


✅ Pros:

 Simple to apply.
 Works well with small samples.
 Widely used in practice.

❌ Cons:

 Assumes normal distribution.


 Sensitive to outliers.
 Only compares means (not variance or distribution shape).

🔹 Real-life Examples

 Checking whether average fuel efficiency of a new car model is different from 15
km/l.
 Comparing exam scores of two teaching methods.
 Testing before and after cholesterol levels of patients given a new diet.

📘 Paired T-Test in R
🔹 What is Paired T-Test?

 A Paired T-Test is used when the same group (or matched pairs) is measured twice.
 Instead of comparing two independent groups, it checks whether the mean difference
between paired observations is significantly different from zero.

🔹 Why use Paired T-Test?

 Reduces variability because each subject acts as its own control.


 More powerful than a two-sample t-test when proper pairing exists.
 Detects small changes in treatment/intervention effects.

🔹 When to use Paired T-Test?

 Data are continuous (interval/ratio scale).


 Samples are paired: before/after, left/right, twin studies, or matched subjects.
 Differences are approximately normally distributed.
🔹 Steps in R

1. Collect before/after data.


2. Compute difference between pairs.
3. Run [Link](before, after, paired = TRUE).

🔹 R Example
# Exam marks before and after a coaching program
before <- c(70, 75, 68, 72, 74)
after <- c(74, 78, 70, 73, 77)

# Paired T-test
[Link](before, after, paired = TRUE)

🔹 Sample Output
Paired t-test

data: before and after


t = -6.324, df = 4, p-value = 0.003
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval: -5.1 -1.5
mean of the differences = -3.3

🔹 Interpretation

 t = -6.324 → large in magnitude, suggests strong evidence of difference.


 p-value = 0.003 (< 0.05) → reject null hypothesis.
 Mean difference = -3.3 → after coaching, scores increased by ~3.3 points.
 95% CI: -5.1 to -1.5 → improvement likely lies between 1.5 and 5.1 points.

👉 In simple words: The coaching program had a significant positive effect.


🔹 Pros & Cons

✅ Pros:

 Controls subject-level variability.


 Requires fewer subjects than independent tests.
 Directly compares conditions within the same group.

❌ Cons:

 Requires paired/matched design.


 Sensitive to non-normality of differences.
 Missing values can cause problems.

🔹 Real-Life Examples

1. Measuring blood pressure before and after taking medicine.


2. Checking student marks before and after a coaching class.
3. Comparing machine performance before and after maintenance.
4. Measuring pollution levels at the same location before and after restrictions.

Correlation in R
🔹 What is Correlation?

 Correlation measures the strength and direction of a linear relationship between two
continuous variables.
 It answers: “Do two variables move together? If one increases, does the other
increase or decrease?”

🔹 Why use Correlation?

 To test association between two numeric variables.


 To decide if changes in one variable are linked with changes in another.
 Helps in building regression models and predictive analytics.

🔹 When to use Correlation?

 Both variables are continuous (e.g., height & weight, study hours & marks).
 Relationship is expected to be linear.
 No extreme outliers.
 For Pearson’s correlation test: assumes normality.
 For Spearman/Kendall: non-parametric, used when assumptions are violated.
🔹 R Code Example
# Example: Study hours vs Exam marks
hours <- c(2, 3, 4, 5, 6, 7)
marks <- c(50, 55, 60, 65, 70, 78)

# Pearson correlation test


[Link](hours, marks, method = "pearson")

🔹 Sample Output
Pearson's product-moment correlation

data: hours and marks


t = 15.81, df = 4, p-value = 3.1e-05
cor = 0.992
95 percent confidence interval: 0.94 0.998

🔹 Interpretation
 r = 0.992 → Extremely strong positive correlation.
 p-value = 3.1e-05 < 0.05 → Reject H₀ → significant evidence of correlation.
 CI (0.94 to 0.998) → With 95% confidence, the true correlation lies between 0.94 and
0.998.
👉 Common person’s meaning: “More study hours almost certainly lead to more
marks.”

🔹 Pros
 Easy to compute and interpret.
 Basis for regression and predictive modeling.
 Can compare multiple variable pairs.

🔹 Cons
 Only measures linear relationships.
 Cannot imply causation.
 Sensitive to outliers.

🔹 Real-Life Examples
1. Health → Height vs Weight
2. Education → Study hours vs Marks
3. Business → Advertising spend vs Sales
4. Climate → Temperature vs Ice cream sales

Chi-Square Test in R
🔹 1. What is the Chi-Square Test?

 The Chi-Square (χ²) test is a non-parametric test used with categorical data.
 It checks whether there is a significant association between two categorical variables,
or whether observed frequencies differ from expected frequencies.
 Commonly used in contingency tables.

🔹 2. Why do we use it?

 To test independence (e.g., gender vs. product preference).


 To test goodness of fit (whether observed distribution fits expected).
 Useful for survey data, classification counts, categorical experiments.

🔹 3. When to use?

 When variables are categorical (nominal/ordinal).


 When sample size is large enough (expected frequency ≥ 5 in each cell).
 When observations are independent.
🔹 5. Types of Chi-Square Test

1. Chi-Square Test of Independence → Checks if two categorical variables are related.


2. Chi-Square Goodness of Fit Test → Checks if observed distribution fits expected
distribution.

🔹 6. R Implementation

(a) Chi-Square Test of Independence

Dataset Example:

Gender Product A Product B


Male 30 20
Female 15 35

R Code:

# Data in matrix form


data <- matrix(c(30, 20, 15, 35), nrow = 2, byrow = TRUE)

# Add row and column names


dimnames(data) <- list(
Gender = c("Male", "Female"),
Product = c("A", "B")
)

# Chi-square test
[Link](data)

Output:

Pearson's Chi-squared test

X-squared = 7.317, df = 1, p-value = 0.0068


Interpretation:

 p-value = 0.0068 < 0.05 → Reject H₀.


 Conclusion: Gender and product preference are not independent → they are related.

Real-Life Example: Marketing team can see product choice varies by gender.

(b) Chi-Square Goodness of Fit Test

Problem: A dice is rolled 60 times with results:

Face Observed
1 8
2 9
3 10
4 11
5 12
6 10

We expect equal frequency = 60/6 = 10.

R Code:

# Observed values
observed <- c(8, 9, 10, 11, 12, 10)

# Expected values (fair dice → equal probability)


expected <- rep(10, 6)

# Chi-square goodness of fit test


[Link](observed, p = rep(1/6, 6))

Output:

Chi-squared test for given probabilities

X-squared = 1.4, df = 5, p-value = 0.92

Interpretation:

 p-value = 0.92 > 0.05 → Fail to reject H₀.


 Conclusion: Dice outcomes fit expected uniform distribution → dice is fair.

🔹 7. Pros and Cons


Pros:

 Easy to apply.
 No assumption of normal distribution.
 Useful for categorical survey data.
Cons:

 Needs large sample size.


 Only shows association, not strength or direction.
 Sensitive to small expected counts.

🔹 8. Summary
 Chi-Square = Test for categorical data.
 Independence Test → Relationship between two variables.
 Goodness of Fit → Compare observed vs expected distribution.
 R function: [Link]().

ANOVA & Correlation in R


1. Analysis of Variance (ANOVA)

🔹 What

 ANOVA (Analysis of Variance) is a hypothesis test used to compare the means of 3


or more independent groups.
 Null hypothesis (H0H_0): All group means are equal.
 Alternative hypothesis (H1H_1): At least one group mean is different.

🔹 Why

 Running multiple t-tests increases Type I error (false positives).


 ANOVA provides a single test to check group differences.

🔹 When to Use

 More than 2 independent groups.


 Dependent variable is continuous.
 Groups are independent.
 Normality & equal variance assumptions hold.
🔹 R Code
# Sample data: test scores of 3 teaching methods
group <- factor(c(rep("A",5), rep("B",5), rep("C",5)))
scores <- c(78,80,82,79,81, 85,88,90,87,86, 92,95,94,96,93)

# Perform ANOVA
anova_model <- aov(scores ~ group)
summary(anova_model)

🔹 Sample Output
Df Sum Sq Mean Sq F value Pr(>F)
group 2 702.4 351.2 45.67 2.3e-07 ***
Residuals 12 92.3 7.7

🔹 Interpretation

 p<0.05p < 0.05: Reject H0H_0. At least one group mean is significantly different.
 In practice: Teaching method affects scores.
 Post-hoc tests (Tukey’s HSD) are needed to identify which specific groups differ.

🔹 Pros

✅ Handles multiple groups in one test


✅ Reduces error compared to many t-tests
✅ Widely used in experimental design

🔹 Cons

❌ Assumes normality & equal variance


❌ Only indicates that differences exist, not where

🔹 Real-Life Example

 Comparing crop yield from 3 fertilizers.


 Comparing average waiting time in 3 bank branches.

2. Correlation Analysis

🔹 What

 Correlation measures strength & direction of relationship between two variables.


 Value of r ranges from –1 to +1.

🔹 Why

 To understand whether two variables are related (positive, negative, or no relation).


 Used in exploratory analysis before regression.
🔹 When to Use

 Two continuous variables.


 Linear relationship.
 No extreme outliers.

🔹 R Code
# Study hours vs Exam Marks
hours <- c(2,4,6,8,10)
marks <- c(50,55,65,70,80)

# Correlation test
[Link](hours, marks, method = "pearson")

🔹 Sample Output
Pearson's product-moment correlation

t = 7.46, df = 3, p-value = 0.0049


cor = 0.974
95 percent confidence interval: 0.78 0.99

🔹 Interpretation

 r=0.974r = 0.974: Very strong positive correlation.


 p<0.05p < 0.05: Significant relationship.
 Common meaning: More study hours → higher marks.

🔹 Pros

✅ Simple & intuitive


✅ Shows strength & direction
✅ Foundation for regression

🔹 Cons

❌ Only measures linear relation


❌ Does not imply causation
❌ Sensitive to outliers

🔹 Real-Life Example
 Height vs Weight of individuals.
 Advertising spend vs Sales revenue.

✅ Together, ANOVA and Correlation form core hypothesis testing tools:

 ANOVA → compares means of groups


 Correlation → measures relationship between variables

Common questions

Powered by AI

A correlation test would be chosen over a t-test when the goal is to assess the strength and direction of a linear relationship between two continuous variables rather than compare their means. For instance, if you want to determine whether there's an association between study hours and exam scores or height and weight, a correlation test would be appropriate. In contrast, a t-test would be used to compare the means of two groups or pre- and post-intervention outcomes .

The reliability of chi-square tests depends significantly on the sample size. A large sample size is critical because it helps ensure that the expected frequency in each cell of a contingency table is at least 5, which is necessary for the approximation used in chi-square calculations to be valid. If the sample size is too small, the test may lead to inaccurate results or be unable to detect existing relationships. To address this issue, applying a Yates' correction for continuity or using Fisher's exact test for small sample sizes are potential solutions. Ensuring proper planning and data collection to meet the assumptions is also crucial .

The chi-square test of independence evaluates relationships between categorical variables by assessing how likely it is that any observed difference between the sets occurred by chance. It compares the observed frequencies in each category of a contingency table against the expected frequencies, which would occur if the variables were independent. A significant p-value suggests that the variables are not independent and that there is an association between them. This test is commonly used when analyzing survey data or classifying count-based information .

The Pearson correlation coefficient, r, quantifies the strength and direction of a linear relationship between two continuous variables. Its value ranges from -1 to 1, where values close to 1 imply a strong positive correlation, values close to -1 indicate a strong negative correlation, and values around 0 suggest no linear correlation. A high correlation implies that as one variable increases, the other tends to also increase proportionally if positive, or decrease if negative, indicating a strong predictive relationship. However, correlation does not imply causation .

The t-test assumes that the data are approximately normally distributed, and if this assumption is violated, the results may not be reliable, especially with small sample sizes. This non-normality can lead to incorrect p-values and thus inappropriate conclusions. To address this limitation, alternative methods such as non-parametric tests (e.g., the Mann-Whitney U test) can be used, which do not assume normal distribution, or data transformation techniques can be applied, such as log transformation, to approximate normality .

T-tests and ANOVA are both used for comparing means, but they differ in their applications. A t-test compares the means of two groups to check if there is a significant difference between them. In contrast, ANOVA is used to compare the means of three or more groups in a single test to determine if at least one group mean is different from the others. T-tests are simple and effective for two-group comparisons, while ANOVA provides a more robust solution for multiple groups, helping to reduce Type I error that may occur if multiple t-tests were used .

ANOVA is advantageous for analyzing the effects of multiple treatments because it allows comparison of three or more group means in a single test, reducing Type I error compared to multiple t-tests. It handles multiple comparisons efficiently and is a powerful technique for identifying whether any significant differences exist among group means. However, challenges include the assumptions of normality and equal variance across groups. Violations of these assumptions can lead to inaccurate conclusions. Also, while ANOVA indicates that differences exist, it does not specify where they lie, often requiring post-hoc tests for detailed analysis .

The p-value measures the strength of evidence against the null hypothesis. It quantifies the probability of observing a test statistic as extreme as the one obtained, assuming the null hypothesis is true. If the p-value is less than the predefined significance level (α, commonly 0.05), it suggests that the observed data is unlikely under the null hypothesis, leading to its rejection. Conversely, a p-value greater than α implies insufficient evidence to reject the null hypothesis. Thus, the p-value is critical in deciding whether to support or refute the null hypothesis, affecting conclusions drawn from the study .

The primary purpose of hypothesis testing in statistical analysis is to make decisions about population parameters based on sample data. It helps determine whether the observed results are due to chance or indicate true differences. This involves formulating a null hypothesis (H₀) that assumes no effect or difference, and an alternative hypothesis (H₁) that suggests there is an effect or difference. Using statistical tests, a decision is made about which hypothesis is more consistent with the data .

A paired t-test is based on the assumptions that the data are continuous, collected in pairs, and the differences between pairs are approximately normally distributed. It's preferred in experimental designs where each subject serves as their own control, such as before-and-after studies, because it reduces variability and increases statistical power by controlling for subject-level differences. This makes it more powerful than a two-sample t-test for detecting small changes when proper pairing exists .

You might also like