0% found this document useful (0 votes)
2 views16 pages

Chapter4 R Code Reference

The document serves as a reference guide for performing various statistical analyses using R, including hypothesis tests for population means, normality tests, two-sample t-tests, and regression analysis. It provides detailed R code examples for each statistical method, along with the purpose of each test and how to interpret the results. Additionally, it includes syntax references for proportion tests and chi-square tests, making it a comprehensive resource for conducting inferential statistics in R.

Uploaded by

Abenezer Nigusie
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)
2 views16 pages

Chapter4 R Code Reference

The document serves as a reference guide for performing various statistical analyses using R, including hypothesis tests for population means, normality tests, two-sample t-tests, and regression analysis. It provides detailed R code examples for each statistical method, along with the purpose of each test and how to interpret the results. Additionally, it includes syntax references for proportion tests and chi-square tests, making it a comprehensive resource for conducting inferential statistics in R.

Uploaded by

Abenezer Nigusie
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

R Code Reference Guide

Basic Inferential Statistics Using R


Chapter 4 — Complete R Code Compilation
1. Hypothesis Test for a Population Mean (Section 4.2)
These codes perform one-sample t-tests to determine whether a population mean differs from a hypothesized
value.

Example 1 — Salmonella in Ice Cream (Two-Tailed Test)


Purpose: Test if the mean level of Salmonella in ice cream differs from 0.3 MPN/g (two-sided test).

# Read data into R


x <- c(0.593, 0.142, 0.329, 0.691, 0.231, 0.793, 0.519, 0.392, 0.418)

# Perform one-sample t-test (two-sided)


[Link](x, alternative = "[Link]", mu = 0.3)

Example 2 — Car Mileage (Left-Tailed Test)


Purpose: Test if actual car mileage is less than the advertised 17 miles per gallon.

# Read data into R


mpg <- c(11.4, 13.1, 14.7, 14.7, 15.0, 15.5, 15.6, 15.9, 16.0, 16.8)

# Perform one-sample t-test (left-tailed)


[Link](mpg, mu = 17, alt = "less")

Example 3 — Student Photocopy Expenditure (Right-Tailed Test)


Purpose: Test if the mean student photocopy expenditure is greater than 101.75 birr.

# Read data into R


Expenditure <- c(140, 125, 150, 124, 143, 170, 125, 94, 127, 53)

# Perform one-sample t-test (right-tailed)


[Link](Expenditure, mu = 101.75, alt = "greater")

2. Normality Tests (Section 4.3)


These codes test whether sample data follows a normal distribution using graphical and formal statistical
methods.

Graphical Checks for Normality


Purpose: Produce a histogram, Q-Q plot, and boxplot to visually assess normality.
mpg <- c(11.4, 13.1, 14.7, 14.7, 15.0, 15.5, 15.6, 15.9, 16.0, 16.8)

hist(mpg) # Histogram
qqnorm(mpg); qqline(mpg) # Q-Q plot with reference line
boxplot(mpg, horizontal = TRUE) # Horizontal boxplot

Shapiro-Wilk Formal Normality Test


Purpose: Formally test for normality. A p-value > 0.05 indicates the data is likely normally distributed.

# Perform Shapiro-Wilk normality test


[Link](mpg)

3. Two-Sample Independent t-Test (Section 4.4)


These codes compare means of two independent groups to determine if they are statistically different.

Example 1 — Drug Dosage Comparison (Equal Variances)


Purpose: Test whether the mean effectiveness of two drug dosages (300mg vs 600mg) differs, assuming
equal variances.

# Data for dose 300mg


x <- c(284, 279, 289, 292, 287, 295, 285, 279, 306, 298)
# Data for dose 600mg
y <- c(298, 307, 297, 279, 291, 335, 299, 300, 306, 291)

# Two-sample t-test assuming equal variances


[Link](x, y, [Link] = TRUE)

Example 2 — Treatment vs Control Group (Left-Tailed)


Purpose: Compare reaction times between a treatment group and a control group; test if control mean is less
than treatment mean.

# Reaction times for control group


Control <- c(91, 87, 99, 77, 88, 91)
# Reaction times for treatment group
Treat <- c(101, 110, 103, 93, 99, 104)

# Two-sample t-test (left-tailed), equal variances


[Link](Control, Treat, alternative = "less", [Link] = TRUE)

Syntax Variants for Two-Sample t-Test


Purpose: Reference for all variance assumption options in the two-sample t-test.
# Equal variances assumed
[Link](x, y, alt = "[Link]", [Link] = TRUE)

# Unequal variances (Welch's t-test) — explicit


[Link](x, y, alt = "[Link]", [Link] = FALSE)

# Unequal variances (Welch's t-test) — default


[Link](x, y, alt = "[Link]")

4. Test for Equality of Two Variances (Section 4.5)


This code performs an F-test to check whether two population variances are equal — a precondition for the
pooled two-sample t-test.

Purpose: Test H0: sigma_x^2 / sigma_y^2 = 1 vs. HA: ratio != 1, at 5% significance.

x <- c(284, 279, 289, 292, 287, 295, 285, 279, 306, 298)
y <- c(298, 307, 297, 279, 291, 335, 299, 300, 306, 291)

# F-test for equality of variances


[Link](x, y)

5. Matched / Paired Samples t-Test (Section 4.6)


These codes compare means of two dependent (paired) samples, such as before-and-after measurements.

Example 1 — Pre/Post Test Scores (Left-Tailed)


Purpose: Test whether post-course scores are significantly higher than pre-course scores.

pre <- c(77, 56, 64, 60, 57, 53, 67, 62, 65, 66)
post <- c(88, 74, 83, 68, 58, 50, 72, 64, 74, 60)

# Paired t-test (left-tailed: test if pre < post)


[Link](pre, post, paired = TRUE, alt = "less")

Example 2 — Premium vs Regular Gas Mileage (Right-Tailed)


Purpose: Test whether cars get significantly better mileage on premium fuel than regular fuel.

reg <- c(16, 20, 21, 22, 23, 22, 27, 25, 27, 28)
prem <- c(19, 22, 24, 24, 25, 25, 26, 26, 28, 32)

# Paired t-test (right-tailed: test if premium > regular)


[Link](prem, reg, alternative = "greater", paired = TRUE)

6. Hypothesis Test for a Single Population Proportion (Section


4.7)
These codes test whether a population proportion differs from a hypothesized value using the [Link]() or
[Link]() functions.

Example 1 — Proportion of Three-Cell-Phone Households


Purpose: Test if the proportion of households with three cell phones differs from 30% (two-sided, large
sample).

# [Link]: large sample (n > 30), without continuity correction


[Link](x = 43, n = 150, p = 0.3, alt = "[Link]", correct = FALSE)

Example 2 — Beef Curry Food Poisoning Proportion


Purpose: Test if the probability of food poisoning from beef curry differs from 10%.

[Link](x = 447, n = 998, p = 0.1, alt = "[Link]", correct = FALSE)

Function Syntax Reference


Purpose: Syntax for exact (small samples) and approximate (large samples) proportion tests.

# Exact binomial test — use when n is small


[Link](x, n, p = 0.5, alternative = "[Link]")

# Large-sample proportion test (normal approximation)


[Link](x, n, p = p0, alternative = "[Link]", correct = TRUE)

7. Comparing Two Population Proportions (Section 4.8)


These codes test whether proportions from two independent populations are equal.

Example 1 — China vs USA Cultural Attitude Survey


Purpose: Test if the proportions of people supporting financial support of elderly parents differ between China
and the USA.

[Link](
x = c(x1 = 1170, x2 = 110),
n = c(n1 = 1300, n2 = 150),
alternative = "[Link]",
correct = FALSE
)

Example 2 — Early Marriage Support: 2001 vs 2003


Purpose: Test whether the proportion supporting early marriage changed significantly between 2001 and
2003.

[Link](
x = c(x1 = 250, x2 = 250),
n = c(n1 = 600, n2 = 500),
alternative = "[Link]",
correct = FALSE
)

8. Chi-Square Test of Independence (Section 4.9)


These codes test whether two categorical variables are statistically independent.

Example 1 — Student Satisfaction vs. Sex (Raw Data)


Purpose: Test independence of gender and department satisfaction from raw survey data.

Sex <- c("M","M","M","F","M","M","F","M","F","M",


"F","F","F","M","F","M","M","F","M","M",
"F","F","M","F","M","M","F","F")

Satisfaction <- c("Yes","No","Yes","No","Yes","No","Yes","No",


"No","No","Yes","No","Yes","No","No","Yes",
"No","Yes","No","Yes","No","Yes","No","Yes",
"No","Yes","No","No")

# Method 1: From raw data directly


[Link](Sex, Satisfaction, correct = FALSE)

# Method 2: Summarise first, then test


myconttabl <- table(Sex, Satisfaction)
[Link](myconttabl, correct = FALSE)

Example 2 — Employment Status vs Gender (Summarised Data)


Purpose: Test if employment status is associated with gender using contingency table data.

# Build contingency table from summary counts


Employment1 <- rbind(c(160, 440), c(40, 360)) # row-wise
Employment2 <- cbind(c(160, 40), c(440, 360)) # column-wise

# Chi-square test (default uses Yates continuity correction)


[Link](Employment1)
[Link](Employment2)

9. Linear Regression and Correlation Analysis (Section 4.10)


These codes fit simple and multiple linear regression models, check assumptions, and compute correlation
coefficients.

Example 1 — Simple Linear Regression: Nitrogen vs Corn Yield


Purpose: Fit a simple linear regression model relating corn yield to nitrogen fertilizer; extract diagnostics and
make predictions.

# 1. Create data frame


SLRdata <- [Link](
amtNitro = c(22, 26, 23, 29, 20, 15, 18, 32),
yield = c(120, 130, 160, 180, 120, 110, 118, 190)
)

# 2. Fit simple linear regression model


[Link] <- lm(yield ~ amtNitro, data = SLRdata)
summary([Link]) # Model summary

# 3. Extract residuals and fitted values


ordres1 <- residuals([Link]) # Ordinary residuals
studres2 <- rstudent([Link]) # Studentized residuals
standres3 <- rstandard([Link]) # Standardized residuals
yfitvalue <- fitted([Link]) # Fitted (predicted) values

# 4. Regression diagnostic plots


par(mfrow = c(2, 2))
plot(SLRdata$amtNitro, SLRdata$yield,
main = "Scatter plot: Yield vs Nitrogen")
abline([Link]) # Add fitted regression line

plot(yfitvalue, studres2,
main = "Studentized Residuals vs Fitted")

qqnorm(ordres1, main = "Normal Probability Plot of Residuals")


qqline(ordres1)

plot(yfitvalue, ordres1,
main = "Residuals vs Fitted")

# 5. Correlation analysis
cor(SLRdata$amtNitro, SLRdata$yield) # Pearson correlation
[Link](SLRdata$amtNitro, SLRdata$yield) # Correlation significance test

# 6. Prediction for new values of X


newdata <- [Link](amtNitro = c(34, 54))
predict([Link], newdata)

Example 2 — Multiple Linear Regression: Soil Variables vs Rice Yield


Purpose: Fit a multiple linear regression with two predictors (total nitrogen, soil moisture); check
multicollinearity and make predictions.

# 1. Create data frame


MLRdata <- [Link](
TotNitro = c(68.5,45.2,91.3,47.8,46.9,66.1,49.5,52.0,48.9,38.4,
87.9,72.8,88.4,42.9,52.5,85.7,41.3,51.7,89.6,82.7,52.3),
soilmois = c(16.7,16.8,18.2,16.3,17.3,18.2,15.9,17.2,16.6,16.0,
18.3,17.1,17.4,15.8,17.8,18.4,16.5,16.3,18.1,19.1,16),
yield = c(174.4,164.4,244.2,154.6,181.6,207.5,152.8,163.2,145.4,
137.2,241.9,191.1,232,145.3,161.1,209.7,146.4,144,
232.6,224.1,166.5)
)

# 2. Fit multiple linear regression model


fitted.model2 <- lm(yield ~ TotNitro + soilmois, data = MLRdata)
summary(fitted.model2)

# 3. Correlation matrix
Corrmat <- cor(cbind(MLRdata$yield, MLRdata$TotNitro, MLRdata$soilmois))

# 4. Pairwise correlation tests


[Link](MLRdata$yield, MLRdata$TotNitro) # Yield vs Nitrogen
[Link](MLRdata$yield, MLRdata$soilmois) # Yield vs Soil Moisture

# 5. Matrix scatter plot


pairs(~ yield + TotNitro + soilmois, data = MLRdata)
plot(MLRdata)

# 6. Regression diagnostics
ordres1 <- residuals(fitted.model2)
studres2 <- rstudent(fitted.model2)
standres3 <- rstandard(fitted.model2)
yfitvalue <- predict(fitted.model2)

par(mfrow = c(1, 2))


qqnorm(ordres1, main = "Normal Probability Plot of Residuals")
qqline(ordres1)
plot(yfitvalue, studres2, main = "Studentized Residuals vs Fitted")

# 7. Multicollinearity — Variance Inflation Factor (VIF>10 is problematic)


[Link]("car") # Run once to install
library("car")
vif(fitted.model2)

# 8. Outlier detection — Y observations


ti <- rstudent(fitted.model2)
criticalti <- qt(1 - (0.05 / (2 * 21)), 21 - 3 - 1)
ti > criticalti # TRUE = outlying Y observation

# 9. Outlier detection — X observations (leverage)


hii <- hatvalues(fitted.model2)
cutpoint <- (2 * 3) / 21
hii > cutpoint # TRUE = outlying X observation

# 10. All influence measures at once


[Link](fitted.model2)

# 11. Individual influence statistics


dffits(fitted.model2) # DFFITS
dfbetas(fitted.model2) # DFBETAS
covratio(fitted.model2) # Covariance ratio
hatvalues(fitted.model2) # Leverage (hat) values
[Link](fitted.model2) # Cook's distance

# 12. All diagnostic plots from fitted model


plot(fitted.model2)

# 13. Prediction
newdata <- [Link](TotNitro = 34, soilmois = 90)
predict(fitted.model2, newdata)

10. Binary Logistic Regression / GLM (Section 4.11)


These codes fit a binary logistic regression model using glm() for a dichotomous outcome variable.

Example — Predictors of Stressed Mind Status


Purpose: Model the probability of being stressed based on age, gender, and education level; compute odds
ratios and confidence intervals.

# Data entry
[Link] <- c(1,1,0,0,0,0,1,1,1,0,1,0,1,0,1,1,0,0,0,1,1,1,1,0,0)
Age <- c(23,32,57,23,34,28,24,35,39,32,43,30,25,36,33,
41,24,27,28,40,23,35,50,35,26)
Gender <- c(1,0,0,1,1,1,0,1,0,0,0,1,1,1,1,0,0,1,1,0,1,1,0,0,0)
[Link] <- c(1,2,2,0,0,0,2,2,2,0,1,1,1,0,0,0,1,0,0,2,1,1,1,1,0)

dataBLRM <- [Link]([Link], Age, Gender, [Link])

# Fit binary logistic regression


fittedBLRM <- glm(
[Link] ~ Age + [Link](Gender) + [Link]([Link]),
family = "binomial",
data = dataBLRM
)
summary(fittedBLRM) # Model output

# Post-estimation: odds ratios and CIs


coef(fittedBLRM) # Model coefficients
exp(coef(fittedBLRM)) # Odds ratios
exp(confint(fittedBLRM)) # 95% CI for odds ratios

# Combined output table


cbind(
coef(fittedBLRM),
odds_ratio = exp(coef(fittedBLRM)),
exp(confint(fittedBLRM))
)

GLM Family / Link Function Reference


Purpose: Reference table for specifying the error distribution in glm().

# Gaussian / Normal outcome (identity link)


glm(y ~ x1 + x2, family = gaussian, data = df)

# Binary / Binomial outcome (logit link)


glm(y ~ x1 + x2, family = binomial("logit"), data = df)

# Count / Poisson outcome (log link)


glm(y ~ x1 + x2, family = poisson("log"), data = df)

11. Analysis of Variance Models (Section 4.12)


These codes perform one-way ANOVA, two-way ANOVA, and Latin square design analyses, including post-hoc
pairwise comparisons.

11a. One-Way ANOVA — Automobile Tyre Lifetime


Purpose: Test whether mean tyre lifetimes differ across four brands; perform Tukey HSD post-hoc
comparisons and diagnostic plots.

# Create data frame


mydata1 <- [Link](
Mileage = c(32.998,36.435,32.777,37.637,36.304,35.915,34.7,
33.523,31.995,35.006,27.879,31.297,31.062,34.838,
34.4456,32.8066,33.415,36.8612,36.9728,35.0814,34.9541,
39.596,38.937,36.124,37.695,36.586,35.967,36.737),
Brands = c(1,1,1,1,1,1,1, 2,2,2,2,2,2,2,
3,3,3,3,3,3,3, 4,4,4,4,4,4,4)
)

# Fit one-way ANOVA


onewayfit <- aov(mydata1$Mileage ~ [Link](mydata1$Brands))
summary(onewayfit) # ANOVA table

# Tukey HSD post-hoc pairwise comparisons


TukeyHSD(onewayfit)

# Test homogeneity of variances (Bartlett test)


[Link](mydata1$Mileage ~ [Link](mydata1$Brands))

# Diagnostic plots
res <- residuals(onewayfit)
fit <- fitted(onewayfit)

qqnorm(res, col = 4, main = "Normal Probability Plot of Residuals")


qqline(res)

plot(fit, res, col = 4, main = "Residuals vs Fitted Values")

11b. Two-Way ANOVA Without Interaction — Reading Test Scores


Purpose: Model reading test scores as a function of form type and school type (two-factor ANOVA without
interaction term).

# Create data frame


mydata <- [Link](
mark = c(75,73,59,69,84, 83,72,56,70,92,
86,61,53,72,88, 73,67,62,79,95),
schooltype = c(1,2,3,4,5, 1,2,3,4,5, 1,2,3,4,5, 1,2,3,4,5),
formtype = c(1,1,1,1,1, 2,2,2,2,2, 3,3,3,3,3, 4,4,4,4,4)
)

# Two-way ANOVA without interaction


twowayanova <- aov(
mark ~ [Link](formtype) + [Link](schooltype),
data = mydata
)
summary(twowayanova)

# Tukey HSD pairwise comparison


TukeyHSD(twowayanova)

11c. Two-Way ANOVA — Biofeedback & Drug on Blood Pressure


Purpose: Test main effects and interaction of biofeedback and drug treatment on blood pressure.

# Create data frame


bpdata <- [Link](
bloodpressure = c(158,163,173,178,168, 188,183,198,178,193,
186,191,196,181,176, 185,190,195,200,180),
biofeedback = c(rep("Present",10), rep("Absent",10)),
drug = c(rep("present",5), rep("absent",5),
rep("present",5), rep("absent",5))
)

# Two-way ANOVA without interaction


Twowayfit <- aov(
bpdata$bloodpressure ~
[Link](bpdata$biofeedback) + [Link](bpdata$drug)
)
summary(Twowayfit)
TukeyHSD(Twowayfit)

# Two-way ANOVA with interaction


TwowayfitIntrxn <- aov(
bpdata$bloodpressure ~
[Link](bpdata$biofeedback) +
[Link](bpdata$drug) +
[Link](bpdata$biofeedback):[Link](bpdata$drug)
)
summary(TwowayfitIntrxn)

11d. Latin Square Design — Assembly Method Comparison


Purpose: Analyse a Latin square design with three factors: operator type, assembly method, and order of
assembly.

# Create data frame


LSDdata <- [Link](
[Link] = c(10,7,5,10, 14,18,10,10, 7,11,11,12, 8,8,9,14),
methodtype = c("C","B","A","D", "D","C","B","A",
"A","D","C","B", "B","A","D","C"),
operatortype = c(rep("op1",4), rep("op2",4),
rep("op3",4), rep("op4",4)),
ordertype = rep(c("or1","or2","or3","or4"), 4)
)

# Fit Latin square design


fitLSD <- aov(
[Link] ~
[Link](operatortype) +
[Link](methodtype) +
[Link](ordertype),
data = LSDdata
)
summary(fitLSD)

12. Time Series Analysis (Section 4.13)


These codes create, plot, test, and model time series data using Box-Jenkins (ARIMA) methodology.

Creating Time Series Objects


Purpose: Convert a numeric vector into an R time series object with appropriate frequency.

# Quarterly data starting Q2 of 1959


Tsdata <- ts(inputData, frequency = 4, start = c(1959, 2))

# Monthly data starting January 1990


Tsdata <- ts(inputData, frequency = 12, start = 1990)

# Annual data from 2009 to 2014


Tsdata <- ts(inputData, start = c(2009), end = c(2014), frequency = 1)
Example — AirPassengers Dataset (Monthly, 1949–1960)
Purpose: Comprehensive time series workflow: data entry, plotting, stationarity testing, differencing, SARIMA
fitting, diagnostics, and forecasting.

# Airline passenger data (monthly 1949-1960)


Airpas <- c(
112,118,132,129,121,135,148,148,136,119,104,118,
115,126,141,135,125,149,170,170,158,184,162,146,
133,114,140,145,150,178,163,172,178,199,199,166,
171,180,193,181,183,218,230,242,209,191,172,194,
196,196,236,235,229,243,264,272,237,211,180,201,
204,188,235,227,234,264,302,293,259,229,203,229,
242,233,267,269,270,315,364,347,312,274,237,278,
284,277,317,313,318,374,413,405,355,306,271,306,
315,301,356,348,355,422,465,467,404,347,305,336,
340,318,362,348,363,435,491,505,404,359,310,337,
360,342,406,396,420,472,548,559,463,407,362,405,
417,391,419,461,472,535,622,606,508,461,390,432
)

# Create time series object


Airpasstsdata <- ts(Airpas, frequency = 12, start = c(1949, 1))

# Plot time series


[Link](Airpasstsdata)
plot(AirPassengers,
ylab = "Number of Passengers (thousands)",
xlab = "Year")

# Log-transform to stabilise variance


logAirpassenger <- log(AirPassengers)
plot(logAirpassenger,
ylab = "log Passengers", xlab = "Year")

# ACF and PACF plots


acf(AirPassengers) # Autocorrelation function
pacf(AirPassengers) # Partial autocorrelation function

# Formal stationarity test (ADF test)


[Link]("tseries") # Run once
library(tseries)
[Link](Airpasstsdata) # p < 0.05 => stationary

# Differencing to achieve stationarity


dAirPassengers <- diff(logAirpassenger) # First difference
d12AirPassengers <- diff(dAirPassengers, lag = 12) # Seasonal difference

# ACF of differenced series


acf(d12AirPassengers,
main = "ACF after Ordinary and Seasonal Differencing",
[Link] = 36)

# Plot differenced series


plot(d12AirPassengers,
main = "Log Ordinary and Seasonal Differenced Data",
ylab = "Differenced Log Passengers")
# Fit SARIMA(0,1,1)x(0,1,1)[12]
fitARIMA <- arima(
logAirpassenger,
order = c(0, 1, 1),
seasonal = list(order = c(0, 1, 1), period = 12)
)
fitARIMA

# Model diagnostics
tsdiag(fitARIMA)

# Forecasting (next 4 years = 48 months)


library(forecast)
forecastAP <- forecast(fitARIMA, level = c(95), h = 48)
autoplot(forecastAP)
plot(forecastAP,
ylab = "Forecasted Passengers (log scale)",
xlab = "Year")

# Back-transform from log scale


forecast_originalscale <- exp(forecastAP$mean)
forecast_originalscale

# Plot back-transformed forecasts


plot(forecast_originalscale, col = 4,
main = "Forecasted Air Passenger Numbers",
type = "b",
ylab = "Passengers",
xlab = "Year")

13. Non-Parametric Tests (Section 4.14)


These codes perform non-parametric alternatives to t-tests and ANOVA when normality assumptions are not met.

13a. Wilcoxon Signed-Rank Test (One-Sample Median Test)


Purpose: Non-parametric analogue of the one-sample t-test. Tests whether the sample median equals a
specified value.

# Mouse weight gain data


weight <- c(17.6, 20.6, 22.2, 15.3, 20.9, 21.0, 18.9, 18.9, 18.9, 18.2)

# Test H0: median = 25 vs HA: median != 25


[Link](weight, mu = 25, alt = "[Link]")

13b. Wilcoxon Rank-Sum Test (Two Independent Samples)


Purpose: Non-parametric analogue of the independent two-sample t-test. Tests whether two groups have the
same population median.
# Student scores under two teaching methods
A <- c(5.8, 1.0, 1.1, 2.1, 2.5, 1.1, 1.0, 1.2, 3.2, 2.7)
B <- c(1.5, 2.7, 6.6, 4.6, 1.1, 1.2, 5.7, 3.2, 1.2, 1.3)

# Test H0: Median_A = Median_B


[Link](A, B) # Two-sided (default)

# For paired data, add: paired = TRUE


# [Link](A, B, paired = TRUE)

13c. Kruskal-Wallis Test (k Independent Groups)


Purpose: Non-parametric analogue of one-way ANOVA. Tests whether k independent groups have the same
population median.

# Exam scores across three different exam types


Mydata <- [Link](
Testscores = c(63,64,95,64,60,85, 58,56,51,84,77, 85,79,59,89,80,71,43),
Examtypes = c( 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3)
)

# Test H0: Median_1 = Median_2 = Median_3


[Link](Testscores ~ Examtypes, data = Mydata)
Quick Reference: R Functions Summary
Key R functions used throughout Chapter 4, grouped by analytical purpose.

Function Purpose Section


[Link]() One-sample, two-sample, or paired t-test 4.2, 4.4, 4.6
[Link]() Shapiro-Wilk normality test 4.3
[Link]() F-test for equality of two variances 4.5
[Link]() One or two proportion tests (large n) 4.7, 4.8
[Link]() Exact binomial proportion test (small n) 4.7
[Link]() Chi-square test of independence 4.9
lm() Fit linear regression model 4.10
summary(model) Display regression/ANOVA results 4.10–4.12
cor() / [Link]() Correlation coefficient and test 4.10
predict() Make predictions from a fitted model 4.10, 4.11
vif() Variance Inflation Factor (multicollinearity) 4.10
[Link]() All outlier/influence statistics together 4.10
glm() Fit generalized linear model (e.g. logistic) 4.11
aov() Fit ANOVA model 4.12
TukeyHSD() Tukey post-hoc pairwise comparisons 4.12
[Link]() Bartlett test for homogeneity of variances 4.12
ts() Create time series object 4.13
[Link]() Plot time series data 4.13
acf() / pacf() ACF and PACF plots 4.13
[Link]() Augmented Dickey-Fuller stationarity test 4.13
diff() Difference a time series 4.13
arima() Fit ARIMA/SARIMA model 4.13
tsdiag() ARIMA model diagnostic plots 4.13
forecast() Generate forecasts from fitted model 4.13
[Link]() Wilcoxon signed-rank or rank-sum test 4.14
[Link]() Kruskal-Wallis test 4.14

End of R Code Reference — Chapter 4: Basic Inferential Statistics Using R

You might also like