Repository Public
1import Foundation2import SheetCore3import Statistics4import AnalysisKit56/// Descriptive summary of one or many columns.7enum DescriptiveSummaryTool {8 static let descriptor: ToolDescriptor = {9 var t = ToolDescriptor(10 id: "describe.summary", title: L("Descriptive Summary"), group: Common.groupDescribe, systemImage: "sum",11 summary: L("Location, spread and shape statistics for one or several numeric columns."),12 fields: [13 .range("data", L("Data range")),14 .columns("vars", L("Variables")),15 .choice("missing", L("Missing values"), [FieldOption("pairwise", L("Use every available value (pairwise)")),16 FieldOption("listwise", L("Drop incomplete rows (listwise)"))],17 help: L("Blank cells, text and errors are missing values.")),18 .percent("level", L("Confidence level"), 0.95, min: 0.5, max: 0.9999),19 ],20 info: [21 L("Skewness and kurtosis are the sample statistics G1 and G2 (Excel SKEW and KURT)."),22 L("Quartiles use linear interpolation (Hyndman–Fan type 7, Excel PERCENTILE.INC)."),23 L("The confidence half-width is t(1−α/2; n−1) · s/√n."),24 ],25 run: run)26 t.demo = { _, v in v.set("data", range: "Regression!A1:G121"); v.set("vars", columns: [0, 1, 2, 3]) }27 return t28 }()2930 static func run(_ input: ToolInput) throws -> ToolResult {31 let frame = try input.frame()32 let cols = try input.columns("vars")33 let policy: MissingPolicy = input.values.choice("missing") == "listwise" ? .listwise : .pairwise34 let level = input.values.number("level")35 let s = try Descriptive.summary(columns: cols.map(\.numbers), names: cols.map(\.name), missing: policy, confidenceLevel: level)3637 typealias Row = (String, (DescriptiveSummary) -> Double?, CellFormat)38 let stats: [Row] = [39 (L("Observations"), { Double($0.count) }, .integer), (L("Missing"), { Double($0.missing) }, .integer),40 (L("Mean"), { $0.mean }, .auto), (L("Standard error of the mean"), { $0.standardError }, .auto),41 (L("Median"), { $0.median }, .auto), (L("Mode"), { $0.mode }, .auto),42 (L("Standard deviation (n − 1)"), { $0.standardDeviation }, .auto), (L("Variance (n − 1)"), { $0.variance }, .auto),43 (L("Coefficient of variation"), { $0.coefficientOfVariation }, .percent(2)),44 (L("Skewness"), { $0.skewness }, .fixed(4)), (L("Excess kurtosis"), { $0.kurtosis }, .fixed(4)),45 (L("Minimum"), { $0.minimum }, .auto), (L("First quartile"), { $0.q1 }, .auto), (L("Third quartile"), { $0.q3 }, .auto),46 (L("Maximum"), { $0.maximum }, .auto), (L("Range"), { $0.range }, .auto), (L("Interquartile range"), { $0.iqr }, .auto),47 (L("Sum"), { $0.sum }, .auto),48 (L("Confidence half-width (%@)", Fmt.percent(level, 1, locale: input.locale)), { $0.confidenceHalfWidth }, .auto),49 ]50 var rows: [[Value]] = [[.text(L("Statistic"))] + s.columns.map { .text($0.name) }]51 var table = ReportTable(title: L("Summary statistics"), rows: [])52 for (i, stat) in stats.enumerated() {53 rows.append([.text(stat.0)] + s.columns.map { .finite(stat.1($0)) })54 table.rowFormats[i + 1] = stat.255 }56 table.rows = rows5758 var blocks: [ResultBlock] = [.table(table)]59 let charts = zip(cols, s.columns).prefix(4).filter { $0.1.count > 1 }.map { col, summary in60 ChartBlock(title: L("Distribution of %@", col.name),61 spec: ChartKit.histogram(col.present, xTitle: col.name, yTitle: L("Frequency")),62 summary: L("Histogram of %@: %d values from %@ to %@, mean %@.", col.name, summary.count,63 Fmt.number(summary.minimum, locale: input.locale), Fmt.number(summary.maximum, locale: input.locale),64 Fmt.number(summary.mean, locale: input.locale)),65 height: 200)66 }67 if !charts.isEmpty { blocks.append(.charts(Array(charts))) }68 var notes = [policy == .listwise69 ? L("Listwise deletion: %d of %d rows are complete and were used for every variable.", s.completeRows ?? 0, frame.rowCount)70 : L("Pairwise policy: each variable uses all of its own non-missing values.")]71 notes.append(L("Blank cells, text and error values are treated as missing."))72 blocks.append(.note(notes))73 return ToolResult(title: L("Descriptive Summary"), subtitle: L("%@ — %d variables", frame.label, cols.count), blocks: blocks, sheetName: L("Summary"))74 }75}76