TANSCHE : SMPTS33 - Mathematical Statistics with R Programming - Unit 5

R Programming Unit 5 – Elementary Statistics

📊 STATISTICS WITH R PROGRAMMING

Madurai Kamaraj University · II B.Sc. Mathematics, III Semester · TANSCHE Syllabus

ARO Study Circle

Chapter 5 · Elementary Statistics

Syllabus: Probability distribution – Z test – F test – t test – Correlation – Regression – Forecasting – Time Series Analysis

5.1 Introduction

Probability is defined as the chance of an event occurring. Many real-time events are subject to probability, whether they occur in the day-to-day life of people or in business. The study of probability and related aspects is highly essential for the effective use of necessary tools for data analysis.

Key Terms:
Experiment: An activity with two or more outcomes that can be specified in advance, but actual occurrence cannot be predicted (e.g., tossing a coin).
Sample Space: The list of all possible outcomes of an experiment (e.g., head or tail when tossing a coin).
Event: The occurrence of a particular outcome or a combination of outcomes.

5.2 Probability Distributions

After data collection, the next stage is to present the data in the form of probability distributions. This facilitates further analysis of data in more meaningful ways. Probability distributions can be classified into:

  • Discrete Probability Distributions: Binomial distribution, Poisson distribution, etc.
  • Continuous Probability Distributions: Exponential distribution, Normal distribution, t-distribution, etc.

5.2.1 Binomial Distribution

The binomial distribution model deals with finding the probability of success of an event which has only two possible outcomes in a series of experiments. It describes the outcome of n independent trials, where each trial has only two outcomes: success or failure.

Formula: \( f(x) = \binom{n}{x} p^x (1-p)^{(n-x)} \quad \text{where } x=0,1,2,\dots,n \)

Built-in Functions in R:
dbinom(x, size, prob, log = FALSE) – probability density
pbinom(q, size, prob, lower.tail = TRUE, log.p = FALSE) – cumulative probability
qbinom(p, size, prob, lower.tail = TRUE, log.p = FALSE) – quantile function
rbinom(n, size, prob) – generates random deviates
# Create a sample of 50 numbers incremented by 1 x <- seq(0, 100, by = 1) # Create the binomial distribution y <- dbinom(x, 100, 0.5) # Plot the graph plot(x, y)
# Probability of getting 25 or less tails from 50 tosses x <- pbinom(25, 50, 0.5) print(x)
[1] 0.5561376
# How many tails will have a probability of 0.75 when coin is tossed 25 times x <- qbinom(0.75, 25, 1/2) print(x)
[1] 14
# Find 4 random values from a sample of 100 with probability 0.25 x <- rbinom(4, 100, 0.25) print(x)
[1] 18 26 24 27

5.2.2 Poisson Distribution

Poisson distribution is a discrete probability distribution used to represent the number of occurrences of an event in one unit of time.

Formula: \( f(x) = \frac{\lambda^x e^{-\lambda}}{x!} \quad \text{where } x=0,1,2,3,\dots \)

lower <- qpois(0.001, lambda = 2.5) upper <- qpois(0.999, lambda = 2.5) n <- seq(lower, upper, 1) q <- seq(0.001, 0.999, 0.001) dPoisson25 <- data.frame(N = n, Density = dpois(n, lambda = 2.5), Distribution = ppois(n, lambda = 2.5)) dPoisson25 qPoisson25 <- data.frame(Q = q, Quantile = qpois(q, lambda = 2.5)) tail(qPoisson25)
N Density Distribution
1 0 0.0820850 0.0820850
2 1 0.2052125 0.2872975
3 2 0.2565156 0.5438131
...

5.2.3 Normal Distribution

Normal distribution is a continuous probability distribution. When plotting a graph with values on the horizontal axis and their counts on the vertical axis, we get a bell-shaped curve.

Formula: \( f(x) = \frac{1}{\sigma\sqrt{2\pi}} e^{-(x-\mu)^2/2\sigma^2} \)

z <- seq(-3.5, 3.5, 0.1) q <- seq(0.001, 0.999, 0.001) dStandardNormal <- data.frame(Z = z, Density = dnorm(z, mean = 0, sd = 1), Distribution = pnorm(z, mean = 0, sd = 1)) head(dStandardNormal) qStandardNormal <- data.frame(Q = q, Quantile = qnorm(q, mean = 0, sd = 1)) head(qStandardNormal)
Z Density Distribution
1 -3.5 0.0008726827 0.0002326291
2 -3.4 0.0012322192 0.0003369293
...

5.2.4 Exponential Distribution

The exponential distribution models the time interval between successive random events. If μ is the mean waiting time, the probability density function is \( f(x) = \frac{1}{\mu} e^{-x/\mu} \).

lower <- floor(qexp(0.001, rate = 0.2)) upper <- ceiling(qexp(0.999, rate = 0.2)) t <- seq(lower, upper, 0.1) q <- seq(0.001, 0.999, 0.001) dexp02 <- data.frame(T = t, Density = dexp(t, rate = 0.2), Distribution = pexp(t, rate = 0.2)) head(dexp02)

5.2.5 Chi-Squared Distribution

The chi-squared distribution with k degrees of freedom is the distribution of the sum of squares of k independent standard normal random variables.

lower <- floor(qchisq(0.001, df = 10)) upper <- ceiling(qchisq(0.999, df = 10)) x <- seq(lower, upper, 0.1) q <- seq(0.001, 0.999, 0.001) dchisq10 <- data.frame(X = x, Density = dchisq(x, df = 10), Distribution = pchisq(x, df = 10)) head(dchisq10)

5.2.6 Student's t-Distribution

Student's t-distribution arises when estimating the mean of a normally distributed population in situations where the sample size is small and population standard deviation is unknown.

lower <- floor(qt(0.001, df = 10)) upper <- ceiling(qt(0.999, df = 10)) x <- seq(lower, upper, 0.1) q <- seq(0.001, 0.999, 0.001) dstudent <- data.frame(X = x, Density = dt(x, df = 10), Distribution = pt(x, df = 10)) head(dstudent)

5.2.7 F Distribution

The F distribution is a right-skewed distribution used most commonly in analysis of variance.

lower <- floor(qf(0.001, df1 = 5, df2 = 10)) upper <- ceiling(qf(0.999, df1 = 5, df2 = 10)) x <- seq(lower, upper, 0.1) q <- seq(0.001, 0.999, 0.001) dfunc <- data.frame(X = x, Density = df(x, df1 = 5, df2 = 10), Distribution = pf(x, df1 = 5, df2 = 10)) head(dfunc)

5.2.8 Uniform Distribution

A uniform distribution (rectangular distribution) has constant probability. The continuous uniform distribution is abbreviated as U(a,b).

Quick Reference Card: Probability Distributions
DistributionDensity FunctionCumulative Function
Binomialdbinom()pbinom()
Poissondpois()ppois()
Normaldnorm()pnorm()
Exponentialdexp()pexp()
Chi-squareddchisq()pchisq()
t-distributiondt()pt()
F-distributiondf()pf()
Uniformdunif()punif()

5.3 Z-Test

The Z-test is used to compare the means of two populations when the variances are known. A built-in function for Z-test is not available in R, so we need to write a custom function.

5.3.1 One Sample Z-Test

z.test1sam <- function(a, mu, var) { n <- length(a) zeta <- (mean(a) - mu) / (sqrt(var / n)) return(zeta) } a <- c(175, 168, 168, 190, 156, 181, 182, 175, 174, 179) z.test1sam(a, 175, 5)
[1] 0.9497155

5.3.2 Two Sample Z-Test

z.test2sam <- function(a, b, var.a, var.b) { n.a <- length(a) n.b <- length(b) zeta <- (mean(a) - mean(b)) / (sqrt(var.a / n.a + var.b / n.b)) return(zeta) } a <- c(175, 168, 168, 190, 156, 181, 182, 175, 174, 179) b <- c(185, 169, 173, 173, 188, 186, 175, 174, 179, 180) z.test2sam(a, b, 5, 8.5)
[1] -2.926254
Interpretation: The value of zeta (-2.926254) is greater than the critical value (1.96 for a two-tailed test at α = 0.05). Hence, we reject the null hypothesis and conclude that the two means are significantly different.

5.4 F-Test

An F-test is any statistical test where the test statistic has an F-distribution under the null hypothesis. It is used to compare the variances of two populations.

a <- c(175, 168, 190, 156, 181, 182, 175, 174, 179) b <- c(120, 180, 125, 188, 130, 190, 110, 185, 112, 188) var.test(b, a) qf(0.95, 9, 9)
F test to compare two variances
data: b and a
F = 14.643, num df = 9, denom df = 9, p-value = 0.0004636
alternative hypothesis: true ratio of variances is not equal to 1
95 percent confidence interval: 3.637133 58.952936
sample estimates: ratio of variances 14.64308

[1] 3.178893
Interpretation: The p-value (0.0004636) is less than 0.05, and F-computed (14.643) is greater than F-tabulated (3.178893). Therefore, we reject the null hypothesis of homogeneity of variances.

5.5 Student's t-Test

A t-test is used to compare the means of two populations when the variances are unknown. It is commonly used with small sample sizes.

Assumptions:
• Both samples are random and independent
• Populations are normally distributed
• Variances are unknown but equal
a <- c(175, 168, 168, 190, 156, 181, 182, 175, 174, 179) b <- c(120, 180, 125, 188, 130, 190, 110, 185, 112, 188) t.test(a, b, var.equal = TRUE, paired = FALSE) qt(0.975, 18)
Two Sample t-test
data: a and b
t = 1.8827, df = 18, p-value = 0.07601
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval: -2.549943 46.549943
sample estimates: mean of x 174.8, mean of y 152.8

[1] 2.100922
Interpretation: The p-value (0.07601) is greater than 0.05, and t-computed (1.8827) is less than t-tabulated (2.100922). Therefore, we accept the null hypothesis that the means are equal.

5.6 Basic Multivariate Analysis

Multivariate Data Analysis refers to any statistical technique used to analyze data that arises from more than one variable. This essentially models reality where each situation, product, or decision involves more than a single variable.

Applications of Multivariate Analysis:
• Consumer and market research
• Quality control and quality assurance across industries
• Process optimization and process control
• Research and development

5.7 Correlation Analysis

Correlation analysis consists of calculating Karl Pearson's correlation coefficient, Spearman coefficient, Kendall coefficient, rank correlation, and auto-correlation. The correlation coefficient measures how two variables are linearly related.

Formula for Sample Correlation Coefficient: \( r_{xy} = \frac{S_{xy}}{S_x S_y} \)

Formula for Population Correlation Coefficient: \( \rho_{xy} = \frac{\sigma_{xy}}{\sigma_x \sigma_y} \)

Properties of Correlation Coefficient:
• Range: -1 to +1
• Close to +1: Positive linear relationship
• Close to -1: Negative linear relationship
• Close to 0: Weak or no linear relationship
x <- c(10, 12, 14, 16, 18, 20, 22, 24, 26, 28) y <- c(20, 30, 37, 50, 56, 78, 89, 100, 120, 110) cor(x, y, method = "pearson") cor(x, y, method = "spearman") cor(x, y, method = "kendall")
[1] 0.9851764
[1] 0.9878788
[1] 0.9555556

5.7.1 Covariance

Covariance measures how two variables are linearly related. Positive covariance indicates a positive linear relationship; negative covariance indicates a negative linear relationship.

x <- c(2, 3, 1, 8, 5, 4, 7, 6) y <- c(4, 5, 7, 3, 6, 8, 2, 1) cov(x, y)
[1] -3.714286
Interpretation: The negative covariance indicates a negative linear relationship between the judges' ratings.

5.7.2 Rank Correlation

Spearman's rank correlation coefficient is used when data is available in the form of ranks.

Formula: \( r_s = 1 - \frac{6\sum_{i=1}^{n}(X_i - Y_i)^2}{n(n^2-1)} \)

x <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) y <- c(2, 4, 5, 1, 3, 6, 7, 9, 10, 8) cor.test(x, y, method = "spearman") cor.test(x, y, method = "kendall") cor.test(x, y, method = "pearson")
Spearman's rank correlation rho: rho = 0.830303, p-value = 0.005557
Kendall's rank correlation tau: tau = 0.6888889, p-value = 0.004687
Pearson's product-moment correlation: cor = 0.830303, p-value = 0.00294

5.7.3 Auto-correlation

Auto-correlation is the correlation between values of the same variable based on related objects. It violates the assumption of instance independence.

x <- c(20, 30, 50, 60, 80, 90, 100, 120, 140, 160) acf.results <- acf(x, type = "correlation", plot = TRUE) acf.results
Autocorrelations of series 'x', by lag
0 1 2 3 4 5 6 7 8 9
1.000 0.682 0.377 0.134 -0.065 -0.214 -0.348 -0.412 -0.400 -0.253

5.7.4 Partial Auto-correlation

The partial autocorrelation function (PACF) gives the partial correlation of a time series with its own lagged values, controlling for the values at all shorter lags.

pacf.results <- pacf(x, type = "c", plot = TRUE) pacf.results

5.8 Regression

Regression is a statistical measure that attempts to determine the strength of the relationship between one dependent variable (Y) and a series of independent variables (X).

5.8.1 Simple Linear Regression

General Equation: \( y = ax + b \)

x <- c(1997, 1998, 1999, 2000, 2001, 2002) y <- c(50, 60, 50, 80, 72, 90) r <- lm(y ~ x) summary(r)
Call: lm(formula = y ~ x)
Coefficients: Estimate Std. Error t value Pr(>|t|)
(Intercept) -15129.200 4401.498 -3.437 0.0264 *
x 7.600 2.201 3.453 0.0260 *
Residual standard error: 9.209 on 4 degrees of freedom
Multiple R-squared: 0.7487, Adjusted R-squared: 0.6859
F-statistic: 11.92 on 1 and 4 DF, p-value: 0.02599
a <- data.frame(x = 2008) result <- predict(r, a) result
1 131.6

5.8.2 Multiple Linear Regression

General Equation: \( y = a + b_1x_1 + b_2x_2 + \dots + b_nx_n \)

df1 <- data.frame(revenue = c(20, 23, 25, 27, 21, 29, 22, 24, 27, 35), force = c(8, 13, 8, 18, 23, 16, 10, 12, 14, 20), expense = c(28, 23, 38, 16, 20, 28, 23, 30, 26, 32)) model <- lm(revenue ~ force + expense, data = df1) summary(model)
Coefficients: (Intercept) 5.1483, force 0.6190, expense 0.4304
Residual standard error: 3.671 on 7 degrees of freedom
Multiple R-squared: 0.4703, Adjusted R-squared: 0.319
F-statistic: 3.108 on 2 and 7 DF, p-value: 0.1082

5.8.3 Logistic Regression

Logistic regression is used when the dependent variable is binary (0 or 1).

df1 <- data.frame(Age = c(30,25,32,40,70,60,38,54,63,57), Height = c(165,180,172,150,169,175,179,168,171,185), Weight = c(68,80,76,54,71,78,84,73,79,90), Smoking = c(0,1,1,1,0,0,1,0,1,0)) model <- glm(Smoking ~ Age + Height + Weight, family = binomial, data = df1) summary(model)

5.8.4 Poisson Regression

Poisson regression is used when the response variable represents counts.

df1 <- data.frame(type = c("B","W","B","W","W","B","W","W","B","W"), speed = c("L","M","H","L","L","M","L","H","H","M"), defective = c(15,18,22,13,15,21,16,17,19,16)) model <- glm(defective ~ type + speed, family = poisson, data = df1) summary(model)

5.9 Analysis of Covariance

Analysis of covariance (ANCOVA) blends ANOVA and regression. It allows comparing one variable in two or more groups while taking into account variability of other variables (covariates).

df1 <- data.frame(volume = c(1000,2225,3816,4123,1126,2307,2116,2114,3983,2102), height = c(53,65,76,86,55,80,64,70,81,74), shuttersetting = c(0,1,1,1,0,0,1,0,1,0)) result1 <- aov(volume ~ height * shuttersetting, data = df1) summary(result1) result2 <- aov(volume ~ height + shuttersetting, data = df1) summary(result2) anova(result1, result2)

5.10 Forecasting

Forecasting uses statistical procedures to predict future values of a time series based on historical trends.

5.10.1 Simple Moving Average

library(TTR) x <- c(24, 30, 27, 24, 39, 45, 42, 51) n <- 3 y <- SMA(x, n) y
[1] NA NA 27 27 30 36 42 46

5.10.2 Weighted Moving Average

library(TTR) x <- c(24, 30, 27, 24, 39, 45, 42, 51) n <- 3 y <- WMA(x, n, wts = c(0.2, 0.3, 0.5)) y
[1] NA NA 27.3 26.1 32.1 39.0 42.3 47.1

5.10.3 Single Exponential Smoothing

library(forecast) y <- c(446.7, 454.5, 455.7, 423.6, 456.3, 440.6, 425.3, 485.1, 506, 526.8, 514.3, 494.2) h <- 12 s <- ses(y, h, initial = "simple", alpha = 0.2) summary(s)

5.11 Time Series Analysis

A time series is a series of data points indexed in time order. Time series data have a natural temporal ordering.

5.11.1 Creating Time Series

birthrate <- c(26, 30, 29, 32, 33, 42, 39, 38, 40, 39) birthrate.ts <- ts(birthrate, start = 2001, end = 2010, frequency = 1) print(birthrate.ts) plot(birthrate.ts, type = "o", xlab = "Year", ylab = "Birth Rate", main = "Birth Rate of a State")
Time Series: Start = 2001, End = 2010, Frequency = 1
[1] 26 30 29 32 33 42 39 38 40 39

5.11.2 Seasonal Decomposition

not.stl <- stl(nottem, s.window = "periodic") plot(not.stl)

5.11.3 Exponential Models

fit1 <- HoltWinters(nottem, beta = FALSE, gamma = FALSE) f1 <- forecast(fit1, 3) fit2 <- HoltWinters(nottem, gamma = FALSE) f2 <- forecast(fit2, 3) fit3 <- HoltWinters(nottem) f3 <- forecast(fit3, 3)

5.11.4 ARIMA Models

library(forecast) fit <- auto.arima(nottem) pred <- forecast(fit, 12) pred accuracy(pred)
Quick Reference Card
TopicKey Functions
Correlationcor(), cor.test(), cov()
Auto-correlationacf(), pacf()
Regressionlm(), glm(), predict()
ANCOVAaov(), anova()
Moving AveragesSMA(), WMA() (TTR package)
Exponential Smoothingses(), HoltWinters() (forecast package)
Time Seriests(), stl(), auto.arima()

📘 R Programming · Unit 5 · Elementary Statistics

Prepared by ARO Study Circle

Post a Comment

0 Comments