Skip to content

BCompare groups · ttest.one_sample

One-sample t-test (or z test)

Does the mean differ from a known or hypothesized value?

Tests whether the mean of one numeric variable equals a reference value (μ0), with a confidence interval for the mean and Hedges' g for the standardized difference. Set a known population SD for the z test, or turn on a lens to test equivalence, a minimal effect or non-inferiority.

Verified in Python and R Python and R agree to 10 decimals Also called one-sample z test, z test for a mean, Student's t test (one sample)…

A real result

Example “Sleep”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

One-sample t-testRecorded · Python and R agreeRecorded 2026-11-17 · 19 values compared · largest relative difference 7.9e-13
R

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

Distribution of drug2How is one numeric variable distributed?
View data
drug2
1.900
0.8000
1.100
0.1000
−0.1000
4.400
5.500
1.600
4.600
3.400
Normal Q–Q plot of drug2Is a variable (or a set of residuals) approximately normal, and where does it depart?
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

VariablenMeanSDSEMedian
drug2102.3302.0020.63321.750
  • H0: mean = 0; alternative: two-sided.
Python

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

VariablenMeanSDSEMedian
drug2102.3302.0020.63321.750
  • H0: mean = 0; alternative: two-sided.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Sleepsleep_wide · outcome: drug2
  • Normality anderson darlingmtcars · outcome: mpg
  • Less than 20mtcars · outcome: mpg
  • Missing valuesairquality · outcome: Ozone
  • Z known sigmaa_xy_wide · outcome: x
  • Z greater lens equivalencea_xy_wide · outcome: x
  • Lens equivalencea_xy_wide · outcome: x
  • Lens minimal effectmtcars · outcome: mpg

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • One sample (continuous): one-sample t, Wilcoxon signed-rank · Statistics Guide · B — Compare groups
  • Statistic, p, effect size, CI, adjustment, context · Statistics Guide · Step 4 — Report and interpret
  • Regression (linear, GLM), ANOVA, t-tests, chi-square · DS & ML Decision Guide · Explain — why is it happening?

What you need

Variablenumeric · 1 column
The numeric variable whose mean is tested.

Choices you make

hypothesis

Hypothesized mean (μ0)default 0

The value the mean is tested against (μ0), for example a target or a published norm.

Alternative hypothesisdefault two-sided

Which direction counts as evidence. Keep two-sided unless you fixed the direction before seeing the data.

  • Mean ≠ μ0(default) — Tests for the mean differing from μ0 in either direction; keep it unless you fixed a direction before seeing the data.
  • Mean > μ0 — Tests only for a mean above μ0; pick it only if you fixed this direction before seeing the data.
  • Mean < μ0 — Tests only for a mean below μ0; pick it only if you fixed this direction before seeing the data.
Confidence leveldefault 0.95

How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.

Lensdefault none

Also test against bounds you set before seeing the data: equivalence, a minimal effect or non-inferiority.

  • Off(default) — Test for a difference only.
  • Equivalence (TOST) — Show the effect lies inside your bounds (two one-sided tests).
  • Minimal effect — Show the effect lies outside your bounds, i.e. is big enough to matter.
  • Non-inferiority — Show the effect is not worse than the lower bound.
Lower bound (raw units)default —

The smallest effect that matters on the low side (for non-inferiority: the margin, as a negative number).

Upper bound (raw units)default —

The smallest effect that matters on the high side.

Advanced

Normality checkdefault shapiro_wilk

Which test the normality row uses. Shapiro–Wilk is the most powerful all-rounder; a check, not a gate.

  • Shapiro–Wilk(default) — The default: best overall power for 3–5,000 values.
  • Shapiro–Francia — A simpler Shapiro–Wilk (squared correlation with normal scores); good for heavy tails; 5–5,000 values.
  • Filliben probability-plot correlation — How straight the normal Q–Q plot is (r); p by simulation (fixed seed).
  • Anderson–Darling — Weights the tails heavily; estimated mean and SD; at least 8 values.
  • Lilliefors (Kolmogorov–Smirnov) — The largest gap between the ECDF and the fitted normal; least powerful of the EDF tests.
  • Cramér–von Mises — Squared ECDF gaps summed over the whole range; at least 8 values.
  • D'Agostino–Pearson omnibus (K²) — Combines the skewness and kurtosis z-tests; at least 8 values (20+ preferred).
  • Jarque–Bera — Skewness and kurtosis against a χ²(2); needs large samples to be accurate.
  • D'Agostino skewness — Asymmetry only (z of the sample skewness); at least 8 values.
  • Anscombe–Glynn kurtosis — Tail weight only (z of the sample kurtosis); at least 8 values, rough below 20.
  • Pearson χ² — Counts in equiprobable classes of the fitted normal; weakest of the eleven.
Known population SD (z test)default —

Only when σ is truly known from outside these data (a calibrated process); estimating it from the sample calls for the t test.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Normality

    Shapiro–Wilk by default (choose another test under Normality check); the test is robust with 30 or more values.

    • If violated → Sign test — Uses only whether values lie above or below the reference, so it makes no distributional assumption. Changes the question: Tests the median rather than the mean.
    • If violated → Bootstrap interval for the mean — Resamples the data instead of assuming a normal sampling distribution (BCa interval).
    • If violated → Investigate outliers — Non-normality often comes from a few extreme values; check them before choosing a method.
  • Independent observations

What it reports

  • Tests: Mean differs from the reference value
t
An estimate divided by its standard error, compared with a t distribution.
df
How much independent information is left to estimate variability after fitting the model.
p
How surprising your data would be if the null hypothesis were true, as a probability.
z
An estimate in standard-error units, compared with the standard normal distribution.
sigma
The distance between two distributions' average kernel embeddings; zero when they are equal.
mean
The sum divided by the count; the balance point of the data, pulled by extreme values.
sd
The typical distance of values from their mean, in the data's own units.
se
The typical size of the error in an estimate, the standard deviation of its sampling distribution.
n
How many independent units the analysis used; it sets precision and power.
mean_diff
One group's mean minus another's, in the outcome's own units.
ci_low
A range of effect values compatible with your data at the chosen confidence level.
ci_high
A range of effect values compatible with your data at the chosen confidence level.
cohens_d
A difference in means expressed in standard deviations.
hedges_g
The mean difference divided by the pooled SD, multiplied by a small-sample correction J that removes Cohen's d's upward bias.
g_ci_low
A range of effect values compatible with your data at the chosen confidence level.
g_ci_high
A range of effect values compatible with your data at the chosen confidence level.
sw_w
A test of normality; a small p-value says the data are unlikely to come from a normal distribution.
sw_p
A test of normality; a small p-value says the data are unlikely to come from a normal distribution.
mu
A model of how big the next move is likely to be, built from recent shocks and recent volatility. It says nothing about direction.

Per group, level or term: normality_p (when a non-default normality check is chosen), lens_p (when a lens is on), lens_ci_low (when a lens is on), lens_ci_high (when a lens is on), lens_verdict (when a lens is on)

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • Effect-size intervals invert the noncentral t (scipy: Boost nct; R: AS 243).
Python

The exact script CodeSplash ran for example “Sleep” · 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")})],
})
R

The exact script CodeSplash ran for example “Sleep” · 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"))))
))

Sources

  • Student (1908). The probable error of a mean. Biometrika, 6, 1–25.
  • Steiger, J. H., & Fouladi, R. T. (1997). Noncentrality interval estimation and the evaluation of statistical models.

From the CodeSplash method registry · ttest.one_sample v1.2.1.