SPB Git

Repository Public

Summary.swift 6.8 KB 133 lines swift

1import Foundation2import SheetCore34/// Descriptive statistics of one variable (the rows of Excel's "Descriptive Statistics" tool and a few more).5public struct DescriptiveSummary: Sendable, Hashable, Codable, TableReport {6    public var name: String7    /// Non-missing observations.8    public var count: Int9    /// Missing (NaN) observations that were skipped.10    public var missing: Int11    public var mean: Double12    public var standardError: Double13    public var median: Double14    /// Smallest most-frequent value; nil when no value repeats.15    public var mode: Double?16    /// Sample standard deviation (n − 1).17    public var standardDeviation: Double18    /// Sample variance (n − 1).19    public var variance: Double20    /// Sample excess kurtosis G₂ (Excel KURT).21    public var kurtosis: Double22    /// Sample skewness G₁ (Excel SKEW).23    public var skewness: Double24    public var range: Double25    public var minimum: Double26    public var maximum: Double27    public var sum: Double28    /// First and third quartiles (type-7 quantiles unless another method was requested).29    public var q1: Double30    public var q3: Double31    public var iqr: Double32    public var coefficientOfVariation: Double33    /// Confidence level of `confidenceHalfWidth`.34    public var confidenceLevel: Double35    /// Half-width of the t confidence interval for the mean: t(1−α/2; n−1) · s/√n (Excel "Confidence Level(95.0%)").36    public var confidenceHalfWidth: Double3738    static let labels = ["Mean", "Standard Error", "Median", "Mode", "Standard Deviation", "Sample Variance", "Kurtosis", "Skewness",39                         "Range", "Minimum", "Maximum", "Sum", "Count", "Missing", "Q1", "Q3", "IQR", "Coefficient of Variation"]4041    var cells: [Value] {42        [Report.num(mean), Report.num(standardError), Report.num(median), mode.map { Report.num($0) } ?? .error(.na),43         Report.num(standardDeviation), Report.num(variance), Report.num(kurtosis), Report.num(skewness), Report.num(range),44         Report.num(minimum), Report.num(maximum), Report.num(sum), Report.int(count), Report.int(missing), Report.num(q1),45         Report.num(q3), Report.num(iqr), Report.num(coefficientOfVariation), Report.num(confidenceHalfWidth)]46    }47    var confidenceLabel: String { String(format: "Confidence Level (%g%%)", confidenceLevel * 100) }4849    public func table() -> [[Value]] {50        var out: [[Value]] = [[.text(name), .blank]]51        for (l, v) in zip(Self.labels + [confidenceLabel], cells) { out.append([.text(l), v]) }52        return out53    }54}5556/// Summaries of several columns side by side.57public struct MultiSummary: Sendable, Hashable, Codable, TableReport {58    public var columns: [DescriptiveSummary]59    public var missingPolicy: MissingPolicy60    /// Rows kept under listwise deletion (nil for pairwise).61    public var completeRows: Int?6263    /// One statistic per row, one variable per column.64    public func table() -> [[Value]] {65        guard let first = columns.first else { return [] }66        var out: [[Value]] = [[.text("Statistic")] + columns.map { .text($0.name) }]67        let labels = DescriptiveSummary.labels + [first.confidenceLabel]68        let cells = columns.map(\.cells)69        for (i, l) in labels.enumerated() { out.append([.text(l)] + cells.map { $0[i] }) }70        return out71    }72}7374extension Descriptive {75    /// Summary of one variable; NaN values are treated as missing and skipped.76    public static func summary(_ x: [Double], name: String = "Variable", confidenceLevel: Double = 0.95,77                               quantileMethod: QuantileMethod = .linear) -> DescriptiveSummary {78        let v = x.filter { !$0.isNaN }79        let s = v.sorted()80        let n = v.count81        let q1 = quantile(sorted: s, 0.25, method: quantileMethod), q3 = quantile(sorted: s, 0.75, method: quantileMethod)82        let se = standardError(v)83        let half = n > 1 ? StudentTDistribution(df: Double(n - 1)).isf((1 - confidenceLevel) / 2) * se : Double.nan84        return DescriptiveSummary(name: name, count: n, missing: x.count - n, mean: mean(v), standardError: se, median: median(v),85                                  mode: mode(v), standardDeviation: standardDeviation(v), variance: variance(v),86                                  kurtosis: kurtosis(v), skewness: skewness(v), range: range(v), minimum: minimum(v),87                                  maximum: maximum(v), sum: n > 0 ? sum(v) : .nan, q1: q1, q3: q3, iqr: q3 - q1,88                                  coefficientOfVariation: coefficientOfVariation(v), confidenceLevel: confidenceLevel,89                                  confidenceHalfWidth: half)90    }9192    /// Summaries of several columns (NaN = missing). `listwise` first drops every row with a missing value in93    /// any column; `pairwise` summarises each column on its own non-missing values.94    public static func summary(columns: [[Double]], names: [String]? = nil, missing: MissingPolicy = .pairwise,95                               confidenceLevel: Double = 0.95, quantileMethod: QuantileMethod = .linear) throws -> MultiSummary {96        guard let n = columns.first?.count, columns.allSatisfy({ $0.count == n }) else {97            throw StatError.invalidInput("columns must be non-empty and of equal length")98        }99        var cols = columns100        var complete: Int?101        if missing == .listwise {102            let keep = completeRows(columns)103            cols = columns.map { c in keep.map { c[$0] } }104            complete = keep.count105        }106        let out = cols.enumerated().map { i, c -> DescriptiveSummary in107            var s = summary(c, name: names?[i] ?? "X\(i + 1)", confidenceLevel: confidenceLevel, quantileMethod: quantileMethod)108            if missing == .listwise { s.missing = n - c.count }109            return s110        }111        return MultiSummary(columns: out, missingPolicy: missing, completeRows: complete)112    }113114    /// Frequency table of `x` over `binCount` equal-width bins spanning [min, max]; the last bin is closed115    /// on the right (NumPy `histogram` convention).116    public static func histogram(_ x: [Double], binCount: Int) -> (edges: [Double], counts: [Int]) {117        guard binCount > 0, let lo = x.min(), let hi = x.max() else { return ([], []) }118        let width = (hi > lo ? hi - lo : 1) / Double(binCount)     // a constant series gets [x − ½, x + ½], like NumPy119        let start = hi > lo ? lo : lo - 0.5120        let edges = (0...binCount).map { start + Double($0) * width }121        var counts = [Int](repeating: 0, count: binCount)122        for v in x {123            var k = Int(((v - start) / width).rounded(.down))124            if k >= binCount { k = binCount - 1 }125            if k < 0 { k = 0 }126            // guard against rounding at the edges127            if k > 0, v < edges[k] { k -= 1 } else if k < binCount - 1, v >= edges[k + 1] { k += 1 }128            counts[k] += 1129        }130        return (edges, counts)131    }132}133
Files main
Menu

Theme