Summaries by group
Split a summary by group, count rows by up to three columns, watch for groups too small to trust, and catch a pattern that reverses when you split.
What runs in CodeSplash
- Descriptive statistics Verified in Python and R
- Cochran–Mantel–Haenszel test (stratified 2 × 2) Verified in Python and R
You will be able to
- Produce descriptive statistics by group
- Spot groups too small to summarize reliably
- Recognize when a pooled pattern reverses within groups
- Count rows by up to three columns with Breakdown, and read its percentages
Split, then summarize
ReadA pooled summary can hide everything interesting. In the penguin data, body mass looks broad and lumpy until you split by species, when Gentoo stands well apart from the other two.
Palmer penguinsAdd a group in Descriptive statistics to get one row per group.
Sepal.Length in setosa: mean 5.01 (SD 0.35), median 5.00 [IQR 4.80–5.20], n = 50. 6 summaries for 2 variables across 3 groups of Species.
- Rows
- 150
- Variables
- 2
Plots
View data
| Species | Sepal.Length |
|---|---|
| setosa | 5.100 |
| setosa | 4.900 |
| setosa | 4.700 |
| setosa | 4.600 |
| setosa | 5 |
| setosa | 5.400 |
| setosa | 4.600 |
| setosa | 5 |
| setosa | 4.400 |
| setosa | 4.900 |
| setosa | 5.400 |
| setosa | 4.800 |
| setosa | 4.800 |
| setosa | 4.300 |
| setosa | 5.800 |
| setosa | 5.700 |
| setosa | 5.400 |
| setosa | 5.100 |
| setosa | 5.700 |
| setosa | 5.100 |
| setosa | 5.400 |
| setosa | 5.100 |
| setosa | 4.600 |
| setosa | 5.100 |
| setosa | 4.800 |
| setosa | 5 |
| setosa | 5 |
| setosa | 5.200 |
| setosa | 5.200 |
| setosa | 4.700 |
| setosa | 4.800 |
| setosa | 5.400 |
| setosa | 5.200 |
| setosa | 5.500 |
| setosa | 4.900 |
| setosa | 5 |
| setosa | 5.500 |
| setosa | 4.900 |
| setosa | 4.400 |
| setosa | 5.100 |
| setosa | 5 |
| setosa | 4.500 |
| setosa | 4.400 |
| setosa | 5 |
| setosa | 5.100 |
| setosa | 4.800 |
| setosa | 5.100 |
| setosa | 4.600 |
| setosa | 5.300 |
| setosa | 5 |
| versicolor | 7 |
| versicolor | 6.400 |
| versicolor | 6.900 |
| versicolor | 5.500 |
| versicolor | 6.500 |
| versicolor | 5.700 |
| versicolor | 6.300 |
| versicolor | 4.900 |
| versicolor | 6.600 |
| versicolor | 5.200 |
First 60 of 150 rows.
Descriptive statistics
| Variable | Species | n | Missing | Mean | SD | SE | CI low | CI high | Median | Q1 | Q3 | Min | Max | Skewness (G1) | SE G1 | Excess kurtosis (G2) | SE G2 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Sepal.Length | setosa | 50 | 0 | 5.006 | 0.3525 | 0.0498 | 4.906 | 5.106 | 5 | 4.800 | 5.200 | 4.300 | 5.800 | 0.1201 | 0.3366 | −0.2527 | 0.6619 |
| Sepal.Length | versicolor | 50 | 0 | 5.936 | 0.5162 | 0.0730 | 5.789 | 6.083 | 5.900 | 5.600 | 6.300 | 4.900 | 7 | 0.1054 | 0.3366 | −0.5330 | 0.6619 |
| Sepal.Length | virginica | 50 | 0 | 6.588 | 0.6359 | 0.0899 | 6.407 | 6.769 | 6.500 | 6.225 | 6.900 | 4.900 | 7.900 | 0.1180 | 0.3366 | 0.0329 | 0.6619 |
| Petal.Width | setosa | 50 | 0 | 0.2460 | 0.1054 | 0.0149 | 0.2160 | 0.2760 | 0.2000 | 0.2000 | 0.3000 | 0.1000 | 0.6000 | 1.254 | 0.3366 | 1.719 | 0.6619 |
| Petal.Width | versicolor | 50 | 0 | 1.326 | 0.1978 | 0.0280 | 1.270 | 1.382 | 1.300 | 1.200 | 1.500 | 1 | 1.800 | −0.0312 | 0.3366 | −0.4101 | 0.6619 |
| Petal.Width | virginica | 50 | 0 | 2.026 | 0.2747 | 0.0388 | 1.948 | 2.104 | 2 | 1.800 | 2.300 | 1.400 | 2.500 | −0.1295 | 0.3366 | −0.6023 | 0.6619 |
Intervals and robust summaries
| Variable | Species | Median CI low | Median CI high | Coverage | SD CI low | SD CI high | IQR | P5 | P95 | Trimmed mean | Winsorized mean | Geometric mean | Harmonic mean | CV | MAD | z G1 | z G2 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Sepal.Length | setosa | 4.900 | 5.100 | 96.7% | 0.2944 | 0.4392 | 0.4000 | 4.400 | 5.610 | 5 | 5 | 4.994 | 4.982 | 0.0704 | 0.2965 | 0.3568 | −0.3818 |
| Sepal.Length | versicolor | 5.700 | 6.100 | 96.7% | 0.4312 | 0.6432 | 0.7000 | 5.045 | 6.755 | 5.910 | 5.926 | 5.914 | 5.892 | 0.0870 | 0.5189 | 0.3131 | −0.8053 |
| Sepal.Length | virginica | 6.300 | 6.700 | 96.7% | 0.5312 | 0.7924 | 0.6750 | 5.745 | 7.700 | 6.547 | 6.588 | 6.558 | 6.527 | 0.0965 | 0.5930 | 0.3506 | 0.0497 |
| Petal.Width | setosa | 0.2000 | 0.2000 | 96.7% | 0.0880 | 0.1313 | 0.1000 | 0.1000 | 0.4000 | 0.2200 | 0.2320 | 0.2266 | 0.2088 | 0.4284 | 0 | 3.725 | 2.597 |
| Petal.Width | versicolor | 1.300 | 1.400 | 96.7% | 0.1652 | 0.2464 | 0.3000 | 1 | 1.600 | 1.340 | 1.344 | 1.311 | 1.296 | 0.1491 | 0.2224 | −0.0926 | −0.6195 |
| Petal.Width | virginica | 1.900 | 2.100 | 96.7% | 0.2294 | 0.3423 | 0.5000 | 1.545 | 2.455 | 2.023 | 2.034 | 2.007 | 1.988 | 0.1356 | 0.2965 | −0.3847 | −0.9099 |
- Mean CI: t interval at 95%; median CI: order statistics (achieved coverage in the table); SD CI: χ², assumes normality.
- Skewness G1 and excess kurtosis G2 are the type-2 estimators with their standard errors; z = G / SE.
- Trimmed and winsorized means use 20% from each end; MAD is scaled by 1/Φ⁻¹(¾).
- Strongly skewed (|G1| ≥ 1): Petal.Width (setosa) — report the median and IQR.
The exact R script · R R version 4.5.1 (2025-06-13)
# Descriptive statistics
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.continuous 1.1.2 · spec 106451f2df6adbae
# Dataset: iris (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
variables <- c("Sepal.Length", "Petal.Width")
g <- "Species"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/iris.parquet", col_select = unique(c(variables, g))))
n_input <- nrow(df)
df[[g]] <- factor(df[[g]], levels = c("setosa", "versicolor", "virginica")) # stored level order
df <- df[!is.na(df[[g]]), , drop = FALSE] # rows without a group are left out; missing values are counted per variable
df[[g]] <- droplevels(df[[g]])
groups <- lapply(levels(df[[g]]), function(lv) list(level = lv, data = df[df[[g]] == lv, , drop = FALSE]))
cs_check_finite_columns(df, variables) # infinite values stop the run (registry/errors.yaml)
warnings <- list()
if (nrow(df) < n_input) {
warnings <- c(warnings, sprintf("%d of %d rows were left out because the group was missing.", n_input - nrow(df), n_input))
}
conf <- 0.95
trim <- 0.2 # trimmed/winsorized mean: floor(trim * n) values from each end
# %% Describe
describe <- function(x, conf) {
# Moments use the type-2 (SAS/SPSS) estimators G1 and G2; quantiles are type 7.
missing <- sum(is.na(x))
x <- x[!is.na(x)]
n <- length(x)
m <- if (n) mean(x) else NaN
s <- if (n > 1) sd(x) else NaN
se <- if (n > 1) s / sqrt(n) else NaN
tcrit <- if (n > 1) qt(1 - (1 - conf) / 2, n - 1) else NaN
q <- if (n) unname(quantile(x, c(0.05, 0.25, 0.5, 0.75, 0.95), type = 7)) else rep(NaN, 5)
mom <- cs_moments(x)
mci <- cs_describe_median_ci(x, conf) # order statistics (sign-test inversion)
sci <- cs_sd_ci(s, n, conf) # chi-square interval (assumes normality)
positive <- n > 0 && all(x > 0)
c(list(n = n, missing = missing, mean = m, sd = s, se = se, ci_low = m - tcrit * se, ci_high = m + tcrit * se,
median = q[3], median_ci_low = mci[1], median_ci_high = mci[2], median_ci_level = mci[3],
q1 = q[2], q3 = q[4], iqr = q[4] - q[2], p05 = q[1], p95 = q[5],
min = if (n) min(x) else NaN, max = if (n) max(x) else NaN,
sd_ci_low = sci[1], sd_ci_high = sci[2],
trimmed_mean = cs_trimmed_mean(x, trim), winsorized_mean = cs_winsorized_mean(x, trim),
geometric_mean = if (positive) exp(mean(log(x))) else NaN,
harmonic_mean = if (positive) n / sum(1 / x) else NaN,
cv = if (n > 1 && m != 0) s / m else NaN,
mad = cs_mad(x)),
mom)
}
rows <- list()
values <- list(n_rows = nrow(df))
for (v in variables) {
for (grp in groups) {
d <- describe(grp$data[[v]], conf)
rows[[length(rows) + 1]] <- c(list(variable = v), if (!is.null(g)) list(group = grp$level), d)
suffix <- if (is.null(g)) sprintf("[%s]", v) else sprintf("[%s|%s]", v, grp$level)
for (k in names(d)) values[[paste0(k, suffix)]] <- d[[k]]
}
}
# %% Result
first <- rows[[1]]
lead <- if (is.null(g)) first$variable else sprintf("%s in %s", first$variable, first$group)
summary <- paste0(
sprintf("%s: mean %.2f (SD %.2f), median %.2f [IQR %.2f–%.2f], n = %d", lead, first$mean, first$sd, first$median, first$q1, first$q3, first$n),
if (first$missing > 0) sprintf(" (%d missing)", first$missing) else "",
sprintf(". %d summar%s for %d variable%s", length(rows), if (length(rows) == 1) "y" else "ies", length(variables), if (length(variables) > 1) "s" else ""),
if (!is.null(g)) sprintf(" across %d groups of %s.", length(groups), g) else "."
)
skewed <- Filter(function(r) is.finite(r$skewness) && abs(r$skewness) >= 1, rows)
notes <- list(
sprintf("Mean CI: t interval at %.0f%%; median CI: order statistics (achieved coverage in the table); SD CI: χ², assumes normality.", conf * 100),
"Skewness G1 and excess kurtosis G2 are the type-2 estimators with their standard errors; z = G / SE.",
sprintf("Trimmed and winsorized means use %.0f%% from each end; MAD is scaled by 1/Φ⁻¹(¾).", trim * 100)
)
if (length(skewed)) {
notes <- c(notes, paste0("Strongly skewed (|G1| ≥ 1): ",
paste(vapply(skewed, function(r) if (is.null(g)) r$variable else sprintf("%s (%s)", r$variable, r$group), ""), collapse = ", "),
" — report the median and IQR."))
}
stat_cols <- list(c("n", "n"), c("missing", "Missing"), c("mean", "Mean"), c("sd", "SD"), c("se", "SE"), c("ci_low", "CI low"),
c("ci_high", "CI high"), c("median", "Median"), c("q1", "Q1"), c("q3", "Q3"), c("min", "Min"), c("max", "Max"),
c("skewness", "Skewness (G1)"), c("skewness_se", "SE G1"), c("kurtosis", "Excess kurtosis (G2)"), c("kurtosis_se", "SE G2"))
columns <- c(
list(list(key = "variable", label = "Variable", type = "string")),
if (!is.null(g)) list(list(key = "group", label = g, type = "string")),
lapply(stat_cols, function(s) list(key = s[1], label = s[2], type = if (s[1] %in% c("n", "missing")) "integer" else "number"))
)
robust_cols <- list(c("median_ci_low", "Median CI low"), c("median_ci_high", "Median CI high"), c("median_ci_level", "Coverage"),
c("sd_ci_low", "SD CI low"), c("sd_ci_high", "SD CI high"), c("iqr", "IQR"), c("p05", "P5"), c("p95", "P95"),
c("trimmed_mean", "Trimmed mean"), c("winsorized_mean", "Winsorized mean"), c("geometric_mean", "Geometric mean"),
c("harmonic_mean", "Harmonic mean"), c("cv", "CV"), c("mad", "MAD"), c("skewness_z", "z G1"), c("kurtosis_z", "z G2"))
robust_columns <- c(
list(list(key = "variable", label = "Variable", type = "string")),
if (!is.null(g)) list(list(key = "group", label = g, type = "string")),
lapply(robust_cols, function(s) list(key = s[1], label = s[2], type = if (s[1] == "median_ci_level") "percent" else "number"))
)
lead_key <- if (is.null(g)) first$variable else sprintf("%s|%s", first$variable, first$group)
values$lead <- lead
values$lead_key <- lead_key
values$n_summaries <- length(rows)
values$n_variables <- length(variables)
values$n_groups <- if (is.null(g)) 1 else length(groups)
v0 <- variables[1]
chart_df <- df[!is.na(df[[v0]]), , drop = FALSE]
chart_rows <- unique(round(seq(1, nrow(chart_df), length.out = min(nrow(chart_df), 5000))))
charts <- if (is.null(g)) {
list(cs_chart("distribution", "histogram", sprintf("Distribution of %s", v0), list(x = cs_col(v0, chart_df[[v0]][chart_rows]))))
} else {
list(cs_chart("distribution", "box-violin", sprintf("%s by %s", v0, g), list(
y = cs_col(v0, chart_df[[v0]][chart_rows]),
group = cs_col(g, as.character(chart_df[[g]][chart_rows]), levels = levels(chart_df[[g]]))
)))
}
cs_publish(list(
method = "describe.continuous",
methodVersion = "1.1.2",
title = "Descriptive statistics",
engine = cs_engine_info("stats", "nanoparquet"),
n = nrow(df),
summary = summary,
statistics = list(list(key = "n_rows", label = "Rows", value = nrow(df)), list(key = "variables", label = "Variables", value = length(variables))),
tables = list(
list(key = "descriptives", title = "Descriptive statistics", columns = columns, rows = rows),
list(key = "robust", title = "Intervals and robust summaries", columns = robust_columns, rows = rows)
),
effectSizes = list(),
assumptions = list(),
warnings = warnings,
notes = notes,
charts = charts,
values = values
))
Sepal.Length in setosa: mean 5.01 (SD 0.35), median 5.00 [IQR 4.80–5.20], n = 50. 6 summaries for 2 variables across 3 groups of Species.
- Rows
- 150
- Variables
- 2
To keep this page light, the plots are shown once, under the R tab.
Descriptive statistics
| Variable | Species | n | Missing | Mean | SD | SE | CI low | CI high | Median | Q1 | Q3 | Min | Max | Skewness (G1) | SE G1 | Excess kurtosis (G2) | SE G2 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Sepal.Length | setosa | 50 | 0 | 5.006 | 0.3525 | 0.0498 | 4.906 | 5.106 | 5 | 4.800 | 5.200 | 4.300 | 5.800 | 0.1201 | 0.3366 | −0.2527 | 0.6619 |
| Sepal.Length | versicolor | 50 | 0 | 5.936 | 0.5162 | 0.0730 | 5.789 | 6.083 | 5.900 | 5.600 | 6.300 | 4.900 | 7 | 0.1054 | 0.3366 | −0.5330 | 0.6619 |
| Sepal.Length | virginica | 50 | 0 | 6.588 | 0.6359 | 0.0899 | 6.407 | 6.769 | 6.500 | 6.225 | 6.900 | 4.900 | 7.900 | 0.1180 | 0.3366 | 0.0329 | 0.6619 |
| Petal.Width | setosa | 50 | 0 | 0.2460 | 0.1054 | 0.0149 | 0.2160 | 0.2760 | 0.2000 | 0.2000 | 0.3000 | 0.1000 | 0.6000 | 1.254 | 0.3366 | 1.719 | 0.6619 |
| Petal.Width | versicolor | 50 | 0 | 1.326 | 0.1978 | 0.0280 | 1.270 | 1.382 | 1.300 | 1.200 | 1.500 | 1 | 1.800 | −0.0312 | 0.3366 | −0.4101 | 0.6619 |
| Petal.Width | virginica | 50 | 0 | 2.026 | 0.2747 | 0.0388 | 1.948 | 2.104 | 2 | 1.800 | 2.300 | 1.400 | 2.500 | −0.1295 | 0.3366 | −0.6023 | 0.6619 |
Intervals and robust summaries
| Variable | Species | Median CI low | Median CI high | Coverage | SD CI low | SD CI high | IQR | P5 | P95 | Trimmed mean | Winsorized mean | Geometric mean | Harmonic mean | CV | MAD | z G1 | z G2 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Sepal.Length | setosa | 4.900 | 5.100 | 96.7% | 0.2944 | 0.4392 | 0.4000 | 4.400 | 5.610 | 5.000 | 5.000 | 4.994 | 4.982 | 0.0704 | 0.2965 | 0.3568 | −0.3818 |
| Sepal.Length | versicolor | 5.700 | 6.100 | 96.7% | 0.4312 | 0.6432 | 0.7000 | 5.045 | 6.755 | 5.910 | 5.926 | 5.914 | 5.892 | 0.0870 | 0.5189 | 0.3131 | −0.8053 |
| Sepal.Length | virginica | 6.300 | 6.700 | 96.7% | 0.5312 | 0.7924 | 0.6750 | 5.745 | 7.700 | 6.547 | 6.588 | 6.558 | 6.527 | 0.0965 | 0.5930 | 0.3506 | 0.0497 |
| Petal.Width | setosa | 0.2000 | 0.2000 | 96.7% | 0.0880 | 0.1313 | 0.1000 | 0.1000 | 0.4000 | 0.2200 | 0.2320 | 0.2266 | 0.2088 | 0.4284 | 0 | 3.725 | 2.597 |
| Petal.Width | versicolor | 1.300 | 1.400 | 96.7% | 0.1652 | 0.2464 | 0.3000 | 1 | 1.600 | 1.340 | 1.344 | 1.311 | 1.296 | 0.1491 | 0.2224 | −0.0926 | −0.6195 |
| Petal.Width | virginica | 1.900 | 2.100 | 96.7% | 0.2294 | 0.3423 | 0.5000 | 1.545 | 2.455 | 2.023 | 2.034 | 2.007 | 1.988 | 0.1356 | 0.2965 | −0.3847 | −0.9099 |
- Mean CI: t interval at 95%; median CI: order statistics (achieved coverage in the table); SD CI: χ², assumes normality.
- Skewness G1 and excess kurtosis G2 are the type-2 estimators with their standard errors; z = G / SE.
- Trimmed and winsorized means use 20% from each end; MAD is scaled by 1/Φ⁻¹(¾).
- Strongly skewed (|G1| ≥ 1): Petal.Width (setosa) — report the median and IQR.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Descriptive statistics
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.continuous 1.1.2 · spec 106451f2df6adbae
# Dataset: iris (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import describe as csd
# %% Data
variables = ["Sepal.Length", "Petal.Width"]
g = "Species"
df = pd.read_parquet("tests/parity/fixtures/iris.parquet", columns=variables + [g] if g not in variables else variables)
n_input = len(df)
df[g] = pd.Categorical(df[g], categories=["setosa", "versicolor", "virginica"]) # stored level order
df = df.dropna(subset=[g]) # rows without a group are left out; missing values are counted per variable
df[g] = df[g].cat.remove_unused_categories()
groups = [(str(lv), df[df[g] == lv]) for lv in df[g].cat.categories]
cs.check_finite_columns(df, variables) # infinite values stop the run (registry/errors.yaml)
warnings = []
if len(df) < n_input:
warnings.append(f"{n_input - len(df)} of {n_input} rows were left out because the group was missing.")
conf = 0.95
trim = 0.2 # trimmed/winsorized mean: floor(trim·n) values from each end
# %% Describe
def describe(x, conf):
"""Moments use the type-2 (SAS/SPSS) estimators G1 and G2; quantiles are type 7."""
missing = int(np.isnan(x).sum())
x = x[~np.isnan(x)]
n = x.size
nan = float("nan")
mean = float(x.mean()) if n else nan
sd = float(x.std(ddof=1)) if n > 1 else nan # pinned: ddof = 1
se = sd / np.sqrt(n) if n > 1 else nan
tcrit = stats.t.ppf(1 - (1 - conf) / 2, n - 1) if n > 1 else nan
q05, q1, med, q3, q95 = (float(v) for v in np.quantile(x, [0.05, 0.25, 0.5, 0.75, 0.95])) if n else (nan,) * 5 # type 7
m = csd.moments(x)
med_lo, med_hi, med_cov = csd.median_ci(x, conf) # order statistics (sign-test inversion)
sd_lo, sd_hi = csd.sd_ci(sd, n, conf) # χ² interval (assumes normality)
positive = n > 0 and bool(np.all(x > 0))
return {
"n": n, "missing": missing, "mean": mean, "sd": sd, "se": se,
"ci_low": mean - tcrit * se, "ci_high": mean + tcrit * se,
"median": med, "median_ci_low": med_lo, "median_ci_high": med_hi, "median_ci_level": med_cov,
"q1": q1, "q3": q3, "iqr": q3 - q1, "p05": q05, "p95": q95,
"min": float(x.min()) if n else nan, "max": float(x.max()) if n else nan,
"sd_ci_low": sd_lo, "sd_ci_high": sd_hi,
"trimmed_mean": csd.trimmed_mean(x, trim), "winsorized_mean": csd.winsorized_mean(x, trim),
"geometric_mean": float(np.exp(np.mean(np.log(x)))) if positive else nan,
"harmonic_mean": float(n / np.sum(1 / x)) if positive else nan,
"cv": sd / mean if n > 1 and mean != 0 else nan,
"mad": csd.mad(x),
**m,
}
rows, values = [], {"n_rows": len(df)}
for v in variables:
for level, part in groups:
d = describe(part[v].to_numpy(dtype=float), conf)
rows.append({"variable": v, **({"group": level} if g else {}), **d})
suffix = f"[{v}]" if g is None else f"[{v}|{level}]"
values.update({f"{k}{suffix}": val for k, val in d.items()})
# %% Result
first = rows[0]
lead = f"{first['variable']}" + (f" in {first['group']}" if g else "")
summary = (
f"{lead}: mean {first['mean']:.2f} (SD {first['sd']:.2f}), median {first['median']:.2f} "
f"[IQR {first['q1']:.2f}–{first['q3']:.2f}], n = {first['n']}"
+ (f" ({first['missing']} missing)" if first["missing"] else "")
+ f". {len(rows)} summar{'y' if len(rows) == 1 else 'ies'} for {len(variables)} variable{'s' if len(variables) > 1 else ''}"
+ (f" across {len(groups)} groups of {g}." if g else ".")
)
skewed = [r for r in rows if np.isfinite(r["skewness"]) and abs(r["skewness"]) >= 1]
notes = [
f"Mean CI: t interval at {conf:.0%}; median CI: order statistics (achieved coverage in the table); SD CI: χ², assumes normality.",
"Skewness G1 and excess kurtosis G2 are the type-2 estimators with their standard errors; z = G / SE.",
f"Trimmed and winsorized means use {trim:.0%} from each end; MAD is scaled by 1/Φ⁻¹(¾).",
]
if skewed:
notes.append("Strongly skewed (|G1| ≥ 1): " + ", ".join(r["variable"] + (f" ({r['group']})" if g else "") for r in skewed) + " — report the median and IQR.")
columns = [{"key": "variable", "label": "Variable", "type": "string"}]
if g:
columns.append({"key": "group", "label": g, "type": "string"})
columns += [
{"key": k, "label": label, "type": "integer" if k in ("n", "missing") else "percent" if k == "median_ci_level" else "number"}
for k, label in [("n", "n"), ("missing", "Missing"), ("mean", "Mean"), ("sd", "SD"), ("se", "SE"), ("ci_low", "CI low"),
("ci_high", "CI high"), ("median", "Median"), ("q1", "Q1"), ("q3", "Q3"), ("min", "Min"), ("max", "Max"),
("skewness", "Skewness (G1)"), ("skewness_se", "SE G1"), ("kurtosis", "Excess kurtosis (G2)"), ("kurtosis_se", "SE G2")]
]
robust_columns = [{"key": "variable", "label": "Variable", "type": "string"}]
if g:
robust_columns.append({"key": "group", "label": g, "type": "string"})
robust_columns += [
{"key": k, "label": label, "type": "percent" if k == "median_ci_level" else "number"}
for k, label in [("median_ci_low", "Median CI low"), ("median_ci_high", "Median CI high"), ("median_ci_level", "Coverage"),
("sd_ci_low", "SD CI low"), ("sd_ci_high", "SD CI high"), ("iqr", "IQR"), ("p05", "P5"), ("p95", "P95"),
("trimmed_mean", "Trimmed mean"), ("winsorized_mean", "Winsorized mean"), ("geometric_mean", "Geometric mean"),
("harmonic_mean", "Harmonic mean"), ("cv", "CV"), ("mad", "MAD"), ("skewness_z", "z G1"), ("kurtosis_z", "z G2")]
]
lead_key = first["variable"] if g is None else f"{first['variable']}|{first['group']}"
values.update({"lead": lead, "lead_key": lead_key, "n_summaries": len(rows), "n_variables": len(variables), "n_groups": len(groups) if g else 1})
v0 = variables[0]
chart_df = df[df[v0].notna()]
chart_rows = np.unique(np.round(np.linspace(0, len(chart_df) - 1, min(len(chart_df), 5000))).astype(int)) if len(chart_df) else np.array([], dtype=int)
if g is None:
charts = [cs.chart("distribution", "histogram", f"Distribution of {v0}", {"x": cs.col(v0, chart_df[v0].to_numpy(dtype=float)[chart_rows])})]
else:
charts = [cs.chart("distribution", "box-violin", f"{v0} by {g}", {
"y": cs.col(v0, chart_df[v0].to_numpy(dtype=float)[chart_rows]),
"group": cs.col(g, chart_df[g].astype(str).to_numpy()[chart_rows], levels=[str(x) for x in chart_df[g].cat.categories]),
})]
cs.publish({
"method": "describe.continuous",
"methodVersion": "1.1.2",
"title": "Descriptive statistics",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": len(df),
"summary": summary,
"statistics": [
{"key": "n_rows", "label": "Rows", "value": len(df)},
{"key": "variables", "label": "Variables", "value": len(variables)},
],
"tables": [
{"key": "descriptives", "title": "Descriptive statistics", "columns": columns, "rows": rows},
{"key": "robust", "title": "Intervals and robust summaries", "columns": robust_columns, "rows": rows},
],
"effectSizes": [],
"assumptions": [],
"warnings": warnings,
"notes": notes,
"charts": charts,
"values": values,
})
Pool or split?
PredictPredict first
Across all penguins, longer bills tend to be shallower: the correlation between bill length and depth is negative. What do you expect within each species?
Reveal
The answer: Positive within every species
Positive in all three species. Gentoo have long, shallow bills, and mixing species creates the negative overall trend. Check the correlation by species on your own copy of the data.
Explore the reversal
ExploreThis reversal is Simpson's paradox. Berkeley's admissions data is the classic case: explore it pooled and split by department, and see how a pooled result can point the other way.
EExplorable · Simpson's paradox: Berkeley admissions
Can a comparison reverse when you split the data into groups?
Overall, men were admitted more often. Within departments, who is usually admitted more often?
View
Commit your prediction above to see the result
Make your prediction to see the result.
Neither view is automatically right. The pooled view answers "across all penguins"; the split view answers "within a species". Decide which question you have, before you look.
How small is too small?
ReadA mean from three penguins isn't a fact about a species. Always show counts next to group summaries. With very small groups, plot the points rather than summarizing them. Small multiples in Charts do this well when there are many groups.
View data
| rt_ms | condition |
|---|---|
| 603 | Congruent |
| 447 | Congruent |
| 635 | Congruent |
| 606 | Congruent |
| 614 | Congruent |
| 551 | Congruent |
| 538 | Congruent |
| 699 | Congruent |
| 545 | Congruent |
| 657 | Congruent |
| 566 | Congruent |
| 548 | Congruent |
| 493 | Congruent |
| 868 | Congruent |
| 605 | Congruent |
| 560 | Congruent |
| 499 | Congruent |
| 538 | Congruent |
| 496 | Congruent |
| 526 | Congruent |
| 454 | Congruent |
| 474 | Congruent |
| 499 | Congruent |
| 485 | Congruent |
| 597 | Congruent |
| 429 | Congruent |
| 506 | Congruent |
| 521 | Congruent |
| 552 | Congruent |
| 473 | Congruent |
| 656 | Congruent |
| 516 | Congruent |
| 577 | Congruent |
| 717 | Congruent |
| 507 | Congruent |
| 508 | Congruent |
| 540 | Congruent |
| 503 | Congruent |
| 753 | Congruent |
| 497 | Congruent |
| 509 | Congruent |
| 551 | Congruent |
| 437 | Congruent |
| 418 | Congruent |
| 616 | Congruent |
| 496 | Congruent |
| 744 | Congruent |
| 426 | Congruent |
| 368 | Congruent |
| 568 | Congruent |
| 595 | Congruent |
| 553 | Congruent |
| 427 | Congruent |
| 513 | Congruent |
| 776 | Congruent |
| 420 | Congruent |
| 537 | Congruent |
| 411 | Congruent |
| 421 | Congruent |
| 540 | Congruent |
First 60 of 180 rows.
In code
Readimport pandas as pd
df = pd.read_csv("penguins.csv")
summary = df.groupby("species")["body_mass"].agg(["count", "mean", "median", "std"])
print(summary)library(dplyr)
df <- read.csv("penguins.csv")
df |>
group_by(species) |>
summarise(
n = sum(!is.na(body_mass)),
mean = mean(body_mass, na.rm = TRUE),
median = median(body_mass, na.rm = TRUE),
sd = sd(body_mass, na.rm = TRUE)
)Try it
In the appAdd the penguin data, and run Descriptive statistics on body_mass with species as the group. Then ask what would change if you also split by sex, and try it.
Notice how few rows are left in some cells once you split twice. Splitting has a price, and the counts tell you what it is.
Count by, beside the grid
In the appOn the Data page, Count by… in the grid toolbar opens BreakdownBreakdownCounts rows by up to three columns beside the Data grid, with subtotals, row and column percentages, heat shading and a chart. beside the grid. It reads "Count rows by" a list of columns: add up to three, and every combination gets its count, with subtotals and a total. Other and Missing always come last.
Show switches between Counts, Row %, Column %, % of total and Count + row % without counting again. Count a number column, or choose Summarize (mean, SD, median…) to get group statistics instead.
Right-click a cell for Filter to these rows, Exclude these rows or Compare with the rest. Test association and Describe by group open the matching method in Analyze, with the grid's filters.
When a split reverses
ExploreCount one column by exactly two others, where the inner one has two values. Breakdown then checks whether the link holds within each level of the outer column, and shows a badge: Holds within, Mostly explained by or Reverses within.
Try it with a yes/no outcome: count it by a yes/no column, then add a third column in front. The badge compares effect sizes and shows no p-value. Press it to open the Cochran–Mantel–Haenszel test in Analyze, which asks the same question with a test.
Check your understanding
CheckpointCheck yourself
A grouped table shows Site C's mean is by far the highest. What should you check first?
Show the answer
Answer: a
Small groups produce extreme means. The count tells you whether this is a finding or noise.
Check yourself
A treatment looks worse overall, and better in both the mild and the severe group. What's the likely explanation?
Show the answer
Answer: b
The pooled figure mixes treatment with severity. Both can be calculated correctly; the question is which one answers yours.
Check yourself
Breakdown counts churned by plan. You want to know which plan loses the largest share of its own customers. Which Show mode answers that?
Show the answer
Answer: b
Row % divides each cell by its row's total, so each plan's churned share is out of that plan's customers. % of total would mix in how big each plan is.
Check yourself
Why does Breakdown show Missing as its own level, last?
Show the answer
Answer: b
Leaving missing rows out changes every percentage silently. Show them, then decide what they mean.
Recap
Recap- Pooled summaries can hide groups, and groups can reverse a pooled pattern.
- Always show counts beside group summaries.
- Choose pooled or split from your question, not from the result.
Concepts in this lesson