SPB Git

Repository Public

TukeyHSD.swift 3.9 KB 74 lines swift

1import Foundation2import SheetCore34/// Tukey's honestly-significant-difference comparisons after a one-way ANOVA.5public struct TukeyHSDResult: Sendable, Hashable, Codable, TableReport {6    public struct Comparison: Sendable, Hashable, Codable {7        public var groupA: String8        public var groupB: String9        /// mean(A) − mean(B).10        public var difference: Double11        /// Studentized range statistic |difference| / √(MSE/2·(1/nA + 1/nB)).12        public var q: Double13        /// Family-wise adjusted p-value: P(Q > q) for the studentized range with (k, N − k) df.14        public var pValue: Double15        public var lower: Double16        public var upper: Double17        public var significant: Bool18    }19    public var comparisons: [Comparison]20    public var groupCount: Int21    public var dfError: Double22    public var meanSquareError: Double23    /// Family-wise confidence level of the simultaneous intervals.24    public var level: Double25    /// Critical value q(level; k, df).26    public var criticalQ: Double27    public var assumptions: [String]2829    public func table() -> [[Value]] {30        var out: [[Value]] = [[.text("Tukey HSD (Tukey–Kramer)")],31                              ["Group A", "Group B", "Mean difference", "q", "Adjusted p-value", "Lower", "Upper", "Significant"].map { Value.text($0) }]32        for c in comparisons {33            out.append([.text(c.groupA), .text(c.groupB), Report.num(c.difference), Report.num(c.q), Report.num(c.pValue),34                        Report.num(c.lower), Report.num(c.upper), .bool(c.significant)])35        }36        out.append([.text("Family-wise confidence level"), Report.num(level)])37        out.append([.text("Critical q"), Report.num(criticalQ)])38        for (i, a) in assumptions.enumerated() { out.append([.text(i == 0 ? "Assumptions" : ""), .text(a)]) }39        return Report.rectangular(out)40    }41}4243extension Inference {44    /// Tukey's HSD for all pairwise differences of group means, with the Tukey–Kramer adjustment for45    /// unequal group sizes. p-values and simultaneous confidence intervals come from the studentized46    /// range distribution with (k, N − k) degrees of freedom and the pooled within-group variance.47    public static func tukeyHSD(_ groups: [[Double]], labels: [String]? = nil, level: Double = 0.95) throws -> TukeyHSDResult {48        guard groups.count >= 2 else { throw StatError.insufficientData("need at least two groups") }49        try checkLevel(level)50        let gs = try groups.enumerated().map { try clean($1, min: 1, "group \($0 + 1)") }51        let k = gs.count, n = gs.reduce(0) { $0 + $1.count }52        guard n > k else { throw StatError.insufficientData("need more observations than groups") }53        let dfe = Double(n - k)54        let mse = gs.reduce(0.0) { $0 + Descriptive.sumSquaredDeviations($1) } / dfe55        guard mse > 0 else { throw StatError.invalidInput("no within-group variation") }56        let dist = StudentizedRangeDistribution(k: k, df: dfe)57        let crit = dist.quantile(level)58        let means = gs.map { Descriptive.mean($0) }59        var comps = [TukeyHSDResult.Comparison]()60        for i in 0..<(k - 1) {61            for j in (i + 1)..<k {62                let se = (mse / 2 * (1 / Double(gs[i].count) + 1 / Double(gs[j].count))).squareRoot()63                let diff = means[i] - means[j]64                let q = abs(diff) / se65                let p = dist.sf(q)66                comps.append(.init(groupA: labels?[i] ?? "Group \(i + 1)", groupB: labels?[j] ?? "Group \(j + 1)", difference: diff, q: q,67                                   pValue: max(0, p), lower: diff - crit * se, upper: diff + crit * se, significant: p < 1 - level))68            }69        }70        return TukeyHSDResult(comparisons: comps, groupCount: k, dfError: dfe, meanSquareError: mse, level: level, criticalQ: crit,71                              assumptions: ["Observations are independent", "Residuals are normal within each group", "Groups have equal variances"])72    }73}74
Files main
Menu

Theme