# ZIRULAB article demo: "JASP, jamovi or R instead of SPSS?"
# Uses R's built-in PlantGrowth data set plus one simulated unbalanced data set.
# Run: Rscript r_stats_demo.R [output_dir]
# Packages: base R (stats) and car (Levene test, Type III tests).
suppressPackageStartupMessages(library(car))
args <- commandArgs(TRUE); out <- if (length(args)) args[1] else "."
cat("R", as.character(getRversion()), "| car", as.character(packageVersion("car")), "\n")
d <- PlantGrowth
write.csv(d, file.path(out, "plantgrowth.csv"), row.names = FALSE)

cat("\n--- descriptive ---\n")
print(aggregate(weight ~ group, d, function(x) round(c(n = length(x), mean = mean(x), sd = sd(x)), 3)))

cat("\n--- assumptions ---\n")
print(by(d$weight, d$group, function(x) round(shapiro.test(x)$p.value, 4)))
cat("Levene center=median:\n"); print(leveneTest(weight ~ group, d))
cat("Levene center=mean:\n");   print(leveneTest(weight ~ group, d, center = mean))

cat("\n--- one-way ANOVA (equal variances) ---\n")
fit <- aov(weight ~ group, d); print(summary(fit))
ss <- summary(fit)[[1]][["Sum Sq"]]; cat("eta squared =", round(ss[1] / sum(ss), 3), "\n")
cat("\n--- Welch ANOVA ---\n"); print(oneway.test(weight ~ group, d))
cat("\n--- Tukey HSD ---\n"); print(TukeyHSD(fit))
cat("\n--- Kruskal-Wallis ---\n"); print(kruskal.test(weight ~ group, d))

cat("\n--- two groups: Student versus Welch (ctrl vs trt1) ---\n")
two <- droplevels(subset(d, group != "trt2"))
print(t.test(weight ~ group, two, var.equal = TRUE))
print(t.test(weight ~ group, two))

cat("\n--- why results differ: unbalanced two-way design, simulated ---\n")
set.seed(2026)
u <- data.frame(A = factor(rep(c("a1", "a2"), times = c(30, 18))),
                B = factor(c(rep(c("b1", "b2"), times = c(22, 8)), rep(c("b1", "b2"), times = c(6, 12)))))
u$y <- 10 + 1.2 * (u$A == "a2") + 0.8 * (u$B == "b2") + 0.9 * (u$A == "a2" & u$B == "b2") + rnorm(48, 0, 1.5)
write.csv(u, file.path(out, "unbalanced_simulated.csv"), row.names = FALSE)
print(table(u$A, u$B))
op <- options(contrasts = c("contr.sum", "contr.poly"))
m <- lm(y ~ A * B, u)
cat("Type I (sequential, A first):\n"); print(anova(m))
cat("Type II:\n");  print(Anova(m, type = 2))
cat("Type III:\n"); print(Anova(m, type = 3))
options(op)
cat("\n--- missing data: listwise vs available ---\n")
v <- d$weight; v[c(3, 14, 25)] <- NA
cat("mean with NA, default:", mean(v), "\n"); cat("mean na.rm=TRUE:", round(mean(v, na.rm = TRUE), 4), "\n")
cat("\n--- quantile definitions on ctrl ---\n")
x <- d$weight[d$group == "ctrl"]
for (t in c(1, 2, 6, 7)) cat("type", t, "Q1 =", quantile(x, .25, type = t), "\n")
