The standard error
The standard deviation describes your data. The standard error describes your estimate. Learn to compute it, and what it costs to shrink it.
What runs in CodeSplash
- STAT008One sample Student t test Runs in CodeSplash
- One-sample t-test (or z test) Verified in Python and R
- Two-sample t-test (Welch / Student, or z test) Verified in Python and R
You will be able to
- Tell the standard deviation apart from the standard error
- Compute the standard error of a mean and of a difference
- Work out how much data it takes to shrink a standard error
Read first
Two spreads
ReadThe standard deviationStandard deviationThe typical distance of values from their mean, in the data's own units. says how much individual values vary. The standard errorStandard errorThe typical size of the error in an estimate, the standard deviation of its sampling distribution. says how much an estimate would vary between samples. It is the standard deviation of the sampling distribution.
For a mean:
In a sleep study of 10 patients, is 2.00 and the standard error is 0.63.
The price of precision
PredictPredict first
You want a standard error one third the size of your current one. How much data do you need?
Reveal
Nine times as much. Because of the square root, . Early data buys a lot of precision, and later data buys less.
Try the square root
ExploreDraw samples and compare the spread of their means at and at . Then try the challenge: find the smallest sample whose standard error is small enough.
AExplorable · Standard error against n
How much more data does it take to halve the uncertainty of a mean?
If you quadruple the sample size, the spread of sample means becomes…
Commit your prediction above to see the result
Make your prediction to see the result.
The standard error of a difference
ReadWhen you compare two independent groups, the noise from both adds up, as squares:
For tooth growth this is 1.93. Dividing the gap of 3.70 by it gives the t statistic, 1.92.
Check your reading
CheckpointCheck yourself
In the sleep study, the standard deviation is 2.00 and there are 10 patients. What is the standard error of the mean? Give two decimals.
Show the answer
Answer: 0.633166644731069
.
Check yourself
You collect more data from the same population. What happens to the standard deviation and the standard error?
Show the answer
Answer: b
More data tells you the population's spread more accurately. It doesn't reduce that spread. Only the uncertainty about your estimate keeps falling.
Check yourself
A chart shows group means with error bars, and you want to show how much individual subjects vary. Which bars should you draw?
Show the answer
Answer: a
Standard deviation bars describe individuals. Standard error bars describe the precision of the mean, and they look deceptively small when samples are large. Always label which you drew.
Find it on a result card
In the appRun a one-sample t test and find the mean, standard deviation and standard error. Hold ⌥ to underline everything on the card that can explain itself.
t(9) = 3.68, p = .005, g = 1.06, 95% CI [0.30, 1.79]
- t
- 3.680
- df
- 9
- p
- .005
- Mean
- 2.330
- 95% CI for the mean
- [0.8977, 3.762]
Effect size
- Hedges' g 1.063 95% CI [0.3021, 1.792] · large
Plots
View data
| drug2 |
|---|
| 1.900 |
| 0.8000 |
| 1.100 |
| 0.1000 |
| −0.1000 |
| 4.400 |
| 5.500 |
| 1.600 |
| 4.600 |
| 3.400 |
View data
| drug2 |
|---|
| 1.900 |
| 0.8000 |
| 1.100 |
| 0.1000 |
| −0.1000 |
| 4.400 |
| 5.500 |
| 1.600 |
| 4.600 |
| 3.400 |
Assumptions
- Normality — Shapiro–Wilk W = 0.919, p = .351.
Descriptives
| Variable | n | Mean | SD | SE | Median |
|---|---|---|---|---|---|
| drug2 | 10 | 2.330 | 2.002 | 0.6332 | 1.750 |
- H0: mean = 0; alternative: two-sided.
The exact R script · R R version 4.5.1 (2025-06-13)
# One-sample t-test (or z test)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ttest.one_sample 1.2.1 · spec 5be7c4f86273042a
# Dataset: sleep_wide (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/sleep_wide.parquet", col_select = c("drug2")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("drug2")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("drug2")) # infinite values stop the run (registry/errors.yaml)
# Normality assumption: the test the dialog selected (`normality_test`). Shapiro-Wilk keeps the
# method's own row; any other choice replaces it (cs_normality_test; a simulated p such as
# Filliben's uses the fixed seed 42, so Python draws the same stream).
normality_test <- "shapiro_wilk"
normality_selected <- function(samples, row_label, small) {
res <- lapply(samples, function(s) cs_normality_test(as.numeric(s), normality_test, 42, 1999))
ok <- Filter(function(r) is.finite(r$p), res)
label <- res[[1]]$label
symbol <- res[[1]]$symbol
if (!length(ok)) {
return(list(row = list(key = "normality", label = row_label, status = "info",
detail = sprintf("%s is not available for these sample sizes.", label)), p = NULL))
}
ps <- vapply(ok, function(r) r$p, 0)
p_min <- min(ps)
bad <- sum(ps < 0.05)
status <- if (bad) (if (small) "warn" else "info") else "pass"
tail <- if (status == "warn") "; consider a rank-based or robust method." else "."
row <- if (length(samples) == 1) {
list(key = "normality", label = row_label, status = status, statistic = ok[[1]]$statistic, p = ok[[1]]$p,
detail = paste0(sprintf("%s %s = %.3f, %s", label, symbol, ok[[1]]$statistic, cs_fmt_p(ok[[1]]$p)), tail))
} else {
list(key = "normality", label = row_label, status = status,
detail = paste0(if (bad) sprintf("%s: p < .05 in %d of %d groups (smallest %s)", label, bad, length(ok), cs_fmt_p(p_min))
else sprintf("%s: p ≥ .05 in every group", label), tail))
}
list(row = row, p = p_min)
}
# %% Helpers
ncp_ci <- function(t, df, conf) {
# CI for the noncentrality parameter of an observed t (Steiger & Fouladi 1997)
solve <- function(prob) {
# P(T <= t | ncp) falls as ncp grows: widen a bracket around t until it straddles prob.
f <- function(ncp) suppressWarnings(pt(t, df, ncp)) - prob
lo <- t - 1
hi <- t + 1
step <- 1
while (f(lo) < 0) {
lo <- lo - step
step <- step * 2
}
step <- 1
while (f(hi) > 0) {
hi <- hi + step
step <- step * 2
}
uniroot(f, c(lo, hi), tol = 1e-12)$root
}
alpha <- 1 - conf
c(solve(1 - alpha / 2), solve(alpha / 2))
}
hedges_j <- function(df) {
# Exact small-sample correction J = gamma(df/2) / (sqrt(df/2) * gamma((df - 1)/2))
exp(lgamma(df / 2) - log(sqrt(df / 2)) - lgamma((df - 1) / 2))
}
magnitude <- function(x, cuts, labels = c("negligible", "small", "medium", "large")) {
# Benchmark label for an effect size (rule set named in the result)
if (is.null(x) || !is.finite(x)) return("undetermined")
labels[findInterval(abs(x), cuts) + 1]
}
# %% Test
y <- "drug2"
x <- df[[y]]
n <- length(x)
alternative <- "two-sided"
conf <- 0.95
mu <- 0 # hypothesized mean
sigma <- NULL # known population SD: z test (guide entry 006); NULL = t test
# The effect size (and the t test) need a sample SD: two values that differ.
if (n < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "A one-sample test", min = 2, n = n)
if (length(unique(x)) < 2) cs_error("CS_E_CONSTANT", column = y)
m <- mean(x)
s <- sd(x)
se <- s / sqrt(n)
if (is.null(sigma)) {
res <- t.test(x, mu = mu, alternative = sub("-", ".", alternative, fixed = TRUE), conf.level = conf)
t <- unname(res$statistic)
dof <- unname(res$parameter)
p <- res$p.value
z <- NULL
ci <- res$conf.int # interval for the mean (one-sided when the test is)
} else {
zr <- cs_z_one(x, sigma, mu, conf, alternative) # z = (mean - mu0) / (sigma / sqrt(n)), normal reference
t <- NULL
dof <- NULL
p <- zr$p
z <- zr$z
ci <- c(zr$ci_low, zr$ci_high)
}
# Lens (equivalence / minimal effect / non-inferiority) on mean - mu0, at alpha = 1 - confidence.
lens_kind <- "none"
lens <- NULL
if (lens_kind != "none") {
lens <- cs_lens(lens_kind, m - mu, if (is.null(sigma)) se else sigma / sqrt(n), dof,
NULL, NULL, 1 - conf)
}
# Effect size: d = (mean - mu) / SD, Hedges' g with the exact J, noncentral-t CI (two-sided).
d <- (m - mu) / s
nc <- ncp_ci(d * sqrt(n), n - 1, conf)
j <- hedges_j(n - 1)
g_est <- d * j
g_low <- nc[1] / sqrt(n) * j
g_high <- nc[2] / sqrt(n) * j
# %% Assumptions
sw <- if (n >= 3 && n <= 5000) shapiro.test(x) else NULL
normality <- if (is.null(sw)) {
list(key = "normality", label = "Normality", status = "info", detail = "Too few (or too many) values for Shapiro–Wilk; inspect a Q–Q plot.")
} else if (sw$p.value < 0.05 && n < 30) {
list(key = "normality", label = "Normality", status = "warn", statistic = unname(sw$statistic), p = sw$p.value,
detail = sprintf("Shapiro–Wilk W = %.3f, %s with fewer than 30 values; consider the Wilcoxon signed-rank test.", sw$statistic, cs_fmt_p(sw$p.value)))
} else if (sw$p.value < 0.05) {
list(key = "normality", label = "Normality", status = "info", statistic = unname(sw$statistic), p = sw$p.value,
detail = sprintf("Shapiro–Wilk %s, but with %d values the t-test is robust.", cs_fmt_p(sw$p.value), n))
} else {
list(key = "normality", label = "Normality", status = "pass", statistic = unname(sw$statistic), p = sw$p.value,
detail = sprintf("Shapiro–Wilk W = %.3f, %s.", sw$statistic, cs_fmt_p(sw$p.value)))
}
assumptions <- list(normality)
if (n < 5) warnings <- c(warnings, "Fewer than 5 values; estimates are unstable.")
normality_p <- NULL
if (normality_test != "shapiro_wilk") {
ns_ <- normality_selected(list(x), "Normality", n < 30)
normality_p <- ns_$p
assumptions <- lapply(assumptions, function(a) if (a$key == "normality") ns_$row else a)
}
# %% Result
alpha <- 1 - conf
pct <- sprintf("%.0f%%", conf * 100)
size <- magnitude(g_est, c(0.2, 0.5, 0.8))
significance <- if (p < alpha) {
sprintf("The mean differs significantly from %s (%s).", format(mu), cs_fmt_p(p))
} else {
sprintf("The data are compatible with a mean of %s (%s).", format(mu), cs_fmt_p(p))
}
summary <- sprintf("Mean %s was %.2f (SD %.2f, n = %d), %s CI [%.2f, %.2f]. %s The standardized difference from %s is %s (g = %.2f).",
y, m, s, n, pct, ci[1], ci[2], significance, format(mu), size, g_est)
if (!is.null(lens)) summary <- paste(summary, sprintf("Lens (%s): %s (%s).", gsub("_", " ", lens_kind), lens$lens_verdict, cs_fmt_p(lens$lens_p)))
lead <- if (!is.null(sigma)) sprintf("z = %s", cs_fmt_num(z)) else sprintf("t(%.0f) = %s", dof, cs_fmt_num(t))
values <- list(
t = t, df = dof, p = p, mean = m, sd = s, se = se, n = n, z = z, sigma = sigma,
mean_diff = m - mu, ci_low = ci[1], ci_high = ci[2],
cohens_d = d, hedges_g = g_est, g_ci_low = g_low, g_ci_high = g_high,
sw_w = if (is.null(sw)) NULL else unname(sw$statistic), sw_p = if (is.null(sw)) NULL else sw$p.value,
mu = mu
)
if (!is.null(lens)) values <- c(values, lens)
if (!is.null(normality_p)) values$normality_p <- normality_p
cs_publish(list(
method = "ttest.one_sample",
methodVersion = "1.2.1",
title = if (!is.null(sigma)) "One-sample z-test" else "One-sample t-test",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("%s, %s, g = %s, %s CI [%s, %s]", lead, cs_fmt_p(p), cs_fmt_num(g_est), pct, cs_fmt_num(g_low), cs_fmt_num(g_high)),
statistics = c(
if (!is.null(sigma)) list(list(key = "z", label = "z", value = z))
else list(list(key = "t", label = "t", value = t), list(key = "df", label = "df", value = dof)),
list(list(key = "p", label = "p", value = p, format = "p"),
list(key = "mean", label = "Mean", value = m),
list(key = "ci", label = paste(pct, "CI for the mean"), value = c(ci[1], ci[2]))),
if (!is.null(lens)) list(list(key = "lens_p", label = sprintf("Lens p (%s)", gsub("_", " ", lens_kind)), value = lens$lens_p, format = "p")) else list()
),
tables = list(list(
key = "descriptives", title = "Descriptives",
columns = list(list(key = "variable", label = "Variable", type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "mean", label = "Mean", type = "number"), list(key = "sd", label = "SD", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "median", label = "Median", type = "number")),
rows = data.frame(variable = y, n = n, mean = m, sd = s, se = se, median = unname(quantile(x, 0.5, type = 7)))
)),
effectSizes = list(list(key = "hedges_g", label = "Hedges' g", value = g_est, ciLow = g_low, ciHigh = g_high, ciLevel = conf,
method = "(mean − μ0) / SD, exact J, noncentral-t interval", magnitude = size, ruleSet = "Cohen (1988)")),
assumptions = assumptions,
warnings = warnings,
notes = c(list(sprintf("H0: mean = %s; alternative: %s.", format(mu), alternative)),
if (!is.null(sigma)) list(sprintf("z test with known population SD σ = %s.", format(sigma))) else list(),
if (!is.null(lens)) list(sprintf("The lens interval [%.3g, %.3g] is the %.0f%% interval for mean − μ0.", lens$lens_ci_low, lens$lens_ci_high, (1 - 2 * (1 - conf)) * 100)) else list()),
values = values,
charts = list(cs_chart("distribution", "histogram", sprintf("Distribution of %s", y), list(x = cs_col(y, head(x, 5000), "numeric"))),
cs_chart("qq", "qq", sprintf("Normal Q–Q plot of %s", y), list(x = cs_col(y, head(x, 5000), "numeric"))))
))
t(9) = 3.68, p = .005, g = 1.06, 95% CI [0.30, 1.79]
- t
- 3.680
- df
- 9
- p
- .005
- Mean
- 2.330
- 95% CI for the mean
- [0.8977, 3.762]
Effect size
- Hedges' g 1.063 95% CI [0.3021, 1.792] · large
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Normality — Shapiro–Wilk W = 0.919, p = .351.
Descriptives
| Variable | n | Mean | SD | SE | Median |
|---|---|---|---|---|---|
| drug2 | 10 | 2.330 | 2.002 | 0.6332 | 1.750 |
- H0: mean = 0; alternative: two-sided.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# One-sample t-test (or z test)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ttest.one_sample 1.2.1 · spec 5be7c4f86273042a
# Dataset: sleep_wide (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 optimize, special, stats
import codesplash as cs
from codesplash.stats import means as csm
# %% Data
df = pd.read_parquet("tests/parity/fixtures/sleep_wide.parquet", columns=["drug2"])
n_input = len(df)
df = df.dropna(subset=["drug2"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["drug2"]) # infinite values stop the run (registry/errors.yaml)
# Normality assumption: the test the dialog selected (`normality_test`). Shapiro–Wilk keeps the
# method's own row; any other choice replaces it (codesplash.stats.normality.normality_test; a
# simulated p such as Filliben's uses the fixed seed 42, so R draws the same stream).
normality_test = "shapiro_wilk"
def normality_selected(samples, row_label, small):
from codesplash.stats import normality as csn
res = [csn.normality_test(np.asarray(s, dtype=float), normality_test, 42, 1999) for s in samples]
ok = [r for r in res if np.isfinite(r["p"])]
label, symbol = res[0]["label"], res[0]["symbol"]
if not ok:
return {"key": "normality", "label": row_label, "status": "info", "detail": f"{label} is not available for these sample sizes."}, None
p_min = min(r["p"] for r in ok)
bad = sum(r["p"] < 0.05 for r in ok)
status = ("warn" if small else "info") if bad else "pass"
row = {"key": "normality", "label": row_label, "status": status}
if len(samples) == 1:
row.update({"statistic": ok[0]["statistic"], "p": ok[0]["p"],
"detail": f"{label} {symbol} = {ok[0]['statistic']:.3f}, {cs.fmt_p(ok[0]['p'])}" + ("; consider a rank-based or robust method." if status == "warn" else ".")})
else:
row["detail"] = (f"{label}: p < .05 in {bad} of {len(ok)} groups (smallest {cs.fmt_p(p_min)})" if bad
else f"{label}: p ≥ .05 in every group") + ("; consider a rank-based or robust method." if status == "warn" else ".")
return row, p_min
# %% Helpers
def ncp_ci(t, df, conf):
"""CI for the noncentrality parameter of an observed t (Steiger & Fouladi 1997)."""
def solve(prob):
# P(T <= t | ncp) falls as ncp grows: widen a bracket around t until it straddles prob.
f = lambda ncp: stats.nct.cdf(t, df, ncp) - prob # noqa: E731
lo, hi, step = t - 1.0, t + 1.0, 1.0
while f(lo) < 0:
lo, step = lo - step, step * 2
step = 1.0
while f(hi) > 0:
hi, step = hi + step, step * 2
return optimize.brentq(f, lo, hi, xtol=1e-12)
alpha = 1 - conf
return solve(1 - alpha / 2), solve(alpha / 2)
def hedges_j(df):
"""Exact small-sample correction J = Γ(df/2) / (√(df/2) · Γ((df − 1)/2))."""
return float(np.exp(special.gammaln(df / 2) - np.log(np.sqrt(df / 2)) - special.gammaln((df - 1) / 2)))
def magnitude(x, cuts, labels=("negligible", "small", "medium", "large")):
"""Benchmark label for an effect size (rule set named in the result)."""
if x is None or not np.isfinite(x):
return "undetermined"
for cut, label in zip(cuts, labels):
if abs(x) < cut:
return label
return labels[-1]
# %% Test
y = "drug2"
x = df[y].to_numpy(dtype=float)
n = len(x)
alternative = "two-sided"
conf = 0.95
mu = 0 # hypothesized mean
sigma = None # known population SD: z test (guide entry 006); None = t test
# The effect size (and the t test) need a sample SD: two values that differ.
if n < 2:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="A one-sample test", min=2, n=n)
if len(np.unique(x)) < 2:
cs.cs_error("CS_E_CONSTANT", column=y)
mean, sd = x.mean(), x.std(ddof=1)
se = sd / np.sqrt(n)
if sigma is None:
res = stats.ttest_1samp(x, popmean=mu, alternative=alternative)
ci = res.confidence_interval(confidence_level=conf) # interval for the mean (one-sided when the test is)
t, dof, p, z = float(res.statistic), float(res.df), float(res.pvalue), None
ci_low, ci_high = float(ci.low), float(ci.high)
else:
zr = csm.z_one(x, sigma, mu, conf, alternative) # z = (mean − μ0) / (σ/√n), normal reference
t, dof, p, z = None, None, zr["p"], zr["z"]
ci_low, ci_high = zr["ci_low"], zr["ci_high"]
# Lens (equivalence / minimal effect / non-inferiority) on mean − μ0, at α = 1 − confidence.
lens_kind = "none"
lens = None
if lens_kind != "none":
lens = csm.lens(lens_kind, mean - mu, se if sigma is None else sigma / np.sqrt(n), dof,
None, None, 1 - conf)
# Effect size: d = (mean − mu) / SD, Hedges' g with the exact J, noncentral-t CI (two-sided).
d = (mean - mu) / sd
nc_low, nc_high = ncp_ci(d * np.sqrt(n), n - 1, conf)
j = hedges_j(n - 1)
g_est, g_low, g_high = d * j, nc_low / np.sqrt(n) * j, nc_high / np.sqrt(n) * j
# %% Assumptions
assumptions = []
sw = stats.shapiro(x) if 3 <= n <= 5000 else None
if sw is None:
assumptions.append({"key": "normality", "label": "Normality", "status": "info", "detail": "Too few (or too many) values for Shapiro–Wilk; inspect a Q–Q plot."})
elif sw.pvalue < 0.05 and n < 30:
assumptions.append({"key": "normality", "label": "Normality", "status": "warn", "statistic": float(sw.statistic), "p": float(sw.pvalue),
"detail": f"Shapiro–Wilk W = {sw.statistic:.3f}, {cs.fmt_p(sw.pvalue)} with fewer than 30 values; consider the Wilcoxon signed-rank test."})
elif sw.pvalue < 0.05:
assumptions.append({"key": "normality", "label": "Normality", "status": "info", "statistic": float(sw.statistic), "p": float(sw.pvalue),
"detail": f"Shapiro–Wilk {cs.fmt_p(sw.pvalue)}, but with {n} values the t-test is robust."})
else:
assumptions.append({"key": "normality", "label": "Normality", "status": "pass", "statistic": float(sw.statistic), "p": float(sw.pvalue),
"detail": f"Shapiro–Wilk W = {sw.statistic:.3f}, {cs.fmt_p(sw.pvalue)}."})
if n < 5:
warnings.append("Fewer than 5 values; estimates are unstable.")
normality_p = None
if normality_test != "shapiro_wilk":
_row, normality_p = normality_selected([x], "Normality", n < 30)
assumptions = [_row if a["key"] == "normality" else a for a in assumptions]
# %% Result
alpha = 1 - conf
size = magnitude(g_est, (0.2, 0.5, 0.8))
significance = (
f"The mean differs significantly from {mu:g} ({cs.fmt_p(p)})." if p < alpha
else f"The data are compatible with a mean of {mu:g} ({cs.fmt_p(p)})."
)
summary = (
f"Mean {y} was {mean:.2f} (SD {sd:.2f}, n = {n}), {conf:.0%} CI [{ci_low:.2f}, {ci_high:.2f}]. "
f"{significance} The standardized difference from {mu:g} is {size} (g = {g_est:.2f})."
)
if lens:
summary += f" Lens ({lens_kind.replace('_', ' ')}): {lens['lens_verdict']} ({cs.fmt_p(lens['lens_p'])})."
test_name = "One-sample z-test" if sigma is not None else "One-sample t-test"
lead = f"z = {cs.fmt_num(z)}" if sigma is not None else f"t({dof:.0f}) = {cs.fmt_num(t)}"
cs.publish({
"method": "ttest.one_sample",
"methodVersion": "1.2.1",
"title": test_name,
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"{lead}, {cs.fmt_p(p)}, g = {cs.fmt_num(g_est)}, {conf:.0%} CI [{cs.fmt_num(g_low)}, {cs.fmt_num(g_high)}]",
"statistics": ([{"key": "z", "label": "z", "value": z}] if sigma is not None else
[{"key": "t", "label": "t", "value": t}, {"key": "df", "label": "df", "value": dof}]) + [
{"key": "p", "label": "p", "value": p, "format": "p"},
{"key": "mean", "label": "Mean", "value": mean},
{"key": "ci", "label": f"{conf:.0%} CI for the mean", "value": [ci_low, ci_high]},
] + ([{"key": "lens_p", "label": f"Lens p ({lens_kind.replace('_', ' ')})", "value": lens["lens_p"], "format": "p"}] if lens else []),
"tables": [{
"key": "descriptives", "title": "Descriptives",
"columns": [{"key": "variable", "label": "Variable", "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "mean", "label": "Mean", "type": "number"}, {"key": "sd", "label": "SD", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "median", "label": "Median", "type": "number"}],
"rows": [{"variable": y, "n": n, "mean": mean, "sd": sd, "se": se, "median": float(np.quantile(x, 0.5))}],
}],
"effectSizes": [{"key": "hedges_g", "label": "Hedges' g", "value": g_est, "ciLow": g_low, "ciHigh": g_high, "ciLevel": conf,
"method": "(mean − μ0) / SD, exact J, noncentral-t interval", "magnitude": size, "ruleSet": "Cohen (1988)"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"H0: mean = {mu:g}; alternative: {alternative}."]
+ ([f"z test with known population SD σ = {sigma:g}."] if sigma is not None else [])
+ ([f"The lens interval [{lens['lens_ci_low']:.3g}, {lens['lens_ci_high']:.3g}] is the {1 - 2 * (1 - conf):.0%} interval for mean − μ0."] if lens else []),
"values": {
"t": t, "df": dof, "p": p, "mean": mean, "sd": sd, "se": se, "n": n, "z": z, "sigma": sigma,
"mean_diff": mean - mu, "ci_low": ci_low, "ci_high": ci_high,
"cohens_d": d, "hedges_g": g_est, "g_ci_low": g_low, "g_ci_high": g_high,
"sw_w": None if sw is None else float(sw.statistic), "sw_p": None if sw is None else float(sw.pvalue),
"mu": mu,
**(lens or {}),
**({"normality_p": normality_p} if normality_p is not None else {}),
},
"charts": [cs.chart("distribution", "histogram", f"Distribution of {y}", {"x": cs.col(y, x[:5000], "numeric")}),
cs.chart("qq", "qq", f"Normal Q–Q plot of {y}", {"x": cs.col(y, x[:5000], "numeric")})],
})
Recap
Recap- Standard deviation: how much individuals vary. Standard error: how much an estimate varies.
- The standard error of a mean is , so a third of the error costs nine times the data.
- For a difference between independent groups, add the squared standard errors.
Concepts in this lesson