One mean against a target
Is this mean compatible with a target value? Meet the one-sample t test, and the rarer z test you use when the population spread is known.
What runs in CodeSplash
- STAT006One sample z test for a mean Runs in CodeSplash
- STAT007Two sample z test for means 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
- State the null hypothesis of a one-sample test
- Compute a t statistic from a mean, a standard deviation and n
- Explain when a z test is justified and when t is the honest choice
Read first
A mean and a target
ReadIn the classic sleep study, ten patients took a drug and the extra hours they slept were recorded. The mean gain was 2.33 hours.
Sleep varies from night to night, so a mean above zero could be noise. The question is whether a mean this far from zero is surprising if the drug did nothing:
Here the target is 0. In other studies it is a specification, a benchmark or last year's figure.
Guess the statistic
PredictPredict first
The standard deviation of the gains is 2.00 hours, across 10 patients.
How many standard errors above zero is the mean of 2.33? Drag to your guess.
Make your guess between 0 and 8 standard errors, then reveal.
Reveal
The standard errorStandard errorThe typical size of the error in an estimate, the standard deviation of its sampling distribution. is 2.00 divided by the square root of 10, which is 0.633. The mean is t = 3.68 standard errors above zero.
The statistic
ReadThe top is the distance from the target. The bottom is how much a mean of this size wobbles from sample to sample. Because is itself an estimate, the reference is a t distribution with degrees of freedom, whose heavier tails pay for that uncertainty.
See the tails change
ExploreMove the sample size down and watch the t distribution pull away from the normal curve. Below about 30 observations the difference starts to matter for your p-value.
BExplorable · t against z
Why do small samples need the t distribution instead of the normal?
Guess the two-sided 5% critical value of t for these degrees of freedom.
Commit your prediction above to see the result
Make your prediction to see the result.
Read the result
Readt(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")})],
})
The patients gained 2.33 hours on average (95% CI 0.90 to 3.76), t(9) = 3.68, p = .005. The interval says more than the p-value: gains near zero are not compatible with these data, while gains over three hours are.
When z is honest
ReadA z test replaces with a known population . That is defensible when the spread comes from a long-established process, a calibrated instrument or a published standard, not from the same sample.
Ten readings with mean 5.30 are tested against 5, with known to be 1:
That gives z = 0.949, p = .343. Two groups work the same way: with known spreads, z = 1.215, p = .224.
Check your understanding
CheckpointCheck yourself
A sample of 16 values has standard deviation 2. What is the standard error of the mean? Give your answer to one decimal.
Show the answer
Answer: 0.5
Divide the standard deviation by the square root of n: 2 / 4 = 0.5.
Check yourself
You weighed 12 packets and computed their standard deviation. The label target is 500 g. Which test fits?
Show the answer
Answer: a
Knowing the target is not the same as knowing the spread. A z test needs a population standard deviation from outside the sample.
Check yourself
The 32 cars in mtcars average 20.09 mpg with standard error 1.065. What is the t statistic against a target of 20 mpg? Give two decimals.
Show the answer
Answer: 0.0850600356813336
The mean is only about a tenth of a standard error above 20, so the data are compatible with a target of 20.
Do it in CodeSplash
In the appPick a numeric column and set Hypothesized mean (μ0) to your target. Fill Known population SD (z test) only when the spread comes from outside your data; the method then reports z instead of t.
import numpy as np
import pandas as pd
from scipy import stats
gain = pd.read_csv("sleep_long.csv").query("drug == 'drug 2'")["extra"]
print(stats.ttest_1samp(gain, popmean=0))
# z test: only when sigma comes from outside the sample.
x, mu0, sigma = np.array([4.2, 5.1, 5.4, 4.8, 6, 5.8, 4.9, 5.6, 6.2, 5]), 5, 1
z = (x.mean() - mu0) / (sigma / np.sqrt(len(x)))
print(z, 2 * stats.norm.sf(abs(z)))gain <- sleep$extra[sleep$group == 2]
t.test(gain, mu = 0)
# z test: only when sigma comes from outside the sample.
x <- c(4.2, 5.1, 5.4, 4.8, 6, 5.8, 4.9, 5.6, 6.2, 5); mu0 <- 5; sigma <- 1
z <- (mean(x) - mu0) / (sigma / sqrt(length(x)))
c(z = z, p = 2 * pnorm(-abs(z)))Recap
Recap- A one-sample test asks whether a mean is compatible with a target.
- t uses the sample's own spread and n − 1 degrees of freedom; z needs a spread known from elsewhere.
- Report the mean and its interval, not only p.
Concepts in this lesson