D Appendix E: Solutions to End-of-Chapter Labs

This appendix provides canonical R code solutions for all five End-of-Chapter Labs across the course. Use these solutions to verify your code logic after completing each chapter lab.


D.1 Lab 1 Solutions: R Basics and Data Structures

# 1. Create vectors
student_ids <- 101:105
exam_scores <- c(78.5, 92.0, 84.5, 65.0, 90.0)
pass_status <- factor(c("Pass", "Pass", "Pass", "Fail", "Pass"), 
                      levels = c("Fail", "Pass"), ordered = TRUE)

# 2. Build data frame
grades_df <- data.frame(
  ID = student_ids,
  Score = exam_scores,
  Status = pass_status
)

# 3. Calculate mean of passing students
mean_passing <- mean(grades_df$Score[grades_df$Status == "Pass"])
print(paste("Mean passing score:", round(mean_passing, 2)))

D.2 Lab 2 Solutions: Descriptive Statistics and Data Summaries

# Load dataset
dataset_path <- system.file("extdata", "student_scores.csv", package = "scnpir")
if (dataset_path == "") dataset_path <- "data/student_scores.csv"
scores_df <- read.csv(dataset_path)

# Calculate summary statistics by group
aggregate(score ~ group, data = scores_df, FUN = function(x) {
  c(Mean = mean(x), SD = sd(x), Median = median(x), IQR = IQR(x))
})

D.3 Lab 3 Solutions: Bootstrap Resampling and Confidence Intervals

library(boot)

# Load dataset
income_path <- system.file("extdata", "survey_income.csv", package = "scnpir")
if (income_path == "") income_path <- "data/survey_income.csv"
income_df <- read.csv(income_path)

# Define statistic function for bootstrap median
stat_median <- function(data, indices) {
  median(data[indices, "monthly_income"])
}

# Run 1000 bootstrap iterations
set.seed(42)
boot_results <- boot(data = income_df, statistic = stat_median, R = 1000)

# Compute 95% Percentile Confidence Interval
boot.ci(boot_results, type = c("perc", "basic"))

D.4 Lab 4 Solutions: Analysis of Contingency Tables

# Create 2x2 matrix
trial_data <- matrix(c(45, 15, 20, 40), nrow = 2, byrow = TRUE,
                     dimnames = list(Treatment = c("Drug_A", "Placebo"),
                                     Outcome = c("Recovered", "Not_Recovered")))

# Add margins
addmargins(trial_data)

# Chi-Square test with Yates' continuity correction
chi_res <- chisq.test(trial_data)
print(chi_res)

# Fisher's Exact Test & Odds Ratio
fisher_res <- fisher.test(trial_data)
print(fisher_res)

D.5 Lab 5 Solutions: Non-Parametric Hypothesis Testing

# Load dataset
course_path <- system.file("extdata", "course_dataset.csv", package = "scnpir")
if (course_path == "") course_path <- "data/course_dataset.csv"
course_df <- read.csv(course_path)

# Mann-Whitney U test between New and Standard treatment formats
mw_res <- wilcox.test(baseline_pain ~ treatment, data = course_df, exact = FALSE)
print(mw_res)

# Kruskal-Wallis test across 3 study sites
kw_res <- kruskal.test(baseline_pain ~ site, data = course_df)
print(kw_res)