🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Two-Sample T-Test — Independent Groups Comparison

Hypothesis TestingParametric Tests🟢 Free Lesson

Two-Sample (Independent) T-Test

Hypothesis Testing

Comparing Two Independent Groups

The independent two-sample t-test determines whether two groups have different population means. Choosing between pooled and Welch's versions depends on whether equal variances can be assumed.

  • A/B Testing — Determining whether website changes produce meaningful differences
  • Clinical Trials — Comparing treatment groups in randomized experiments
  • Market Research — Evaluating differences between customer segments

The two-sample t-test is the backbone of comparative research.


What You'll Learn

  • 1State the hypotheses and list the assumptions of the independent samples t-test
  • 2Derive both the pooled and the Welch statistic and explain where their standard errors differ
  • 3Compute the Welch-Satterthwaite degrees of freedom for an unequal-variance comparison
  • 4Report t, df, p, a confidence interval and Cohen's d together, and justify choosing Welch by default

Tests whether two independent groups have equal population means. The design decides everything that follows: subjects must appear in exactly one group, and the two samples must not be matched, ranked, or repeated measures. If the same person is measured twice, this is the wrong test.

The statistic has the same shape in both versions — a difference in means over a standard error — and the two versions differ only in how that standard error is built.

Two Versions of One Statistic

Pooled T-Test (equal variances assumed)

The pooled variance is a weighted average of the two sample variances, weighted by degrees of freedom. Assuming a common population variance lets both samples inform it, which buys a little power when the assumption is true.

Welch's T-Test (unequal variances — default recommendation)

Each variance stays with its own sample, so no assumption is made about a shared . The cost is that the degrees of freedom are no longer a whole number:

This Welch-Satterthwaite formula shrinks df toward the smaller group's degrees of freedom whenever the two variances are very unequal, and recovers when they are equal. Rounding df down is conservative, which is the safe direction.

A Worked Example From Summary Statistics

A trainer compares two coaching programmes on a post-test. Group A has learners with and ; group B has learners with and .

Pooled path.

With the two-sided p-value is 0.130, so the difference is not significant at the 0.05 level.

Welch path.

The p-value at is 0.134 and the 95 percent confidence interval for is , that is from -1.79 to 12.39. Both procedures agree on the conclusion, and they usually will when the variances are similar; the point is that Welch stays correct when they are not.

Assumptions and How Each One Fails

AssumptionWhy it mattersWhat goes wrongRemedy
Independence within and between groupsDefines the two samples as separate evidencePseudoreplication shrinks the standard error dramaticallyCluster-robust errors or a mixed model
Approximate normality of each groupKeeps the t reference distribution accurateStrong skew in small samples distorts p-valuesPermutation test, or Mann-Whitney U
Equal variances, pooled version onlyJustifies pooling the two variancesType I error inflation when n's differUse Welch
Continuous, unbounded outcomeMeans must be meaningfulA ceiling effect compresses one groupTobit or ordinal model

Normality matters least: with balanced groups and per group of about 30 or more, the t-test holds up under considerable skew. Independence matters most, because no amount of sample size repairs a violated independence assumption.

A common workflow is to run Levene's test first and choose the pooled or Welch version from its p-value. Avoid it. That two-stage procedure has no fixed overall Type I error rate, and the choice it makes is nearly irrelevant when you simply default to Welch, which loses almost nothing under equal variances.

Effect Size and Interval Estimation

A p-value alone cannot tell you whether the difference matters. Two quantities complete the picture.

Cohen's d standardises the raw gap by the pooled standard deviation: 0.2 is a small effect, 0.5 medium, 0.8 large. In the worked example , a medium-to-large effect. Hedges' g shrinks d by roughly to remove the small-sample upward bias; at the correction gives .

The confidence interval for the mean difference is the inferential counterpart of the effect size. An interval from -1.79 to 12.39 tells a decision-maker that effects ranging from a small loss to a substantial gain remain compatible with the data — far more informative than "p = 0.134". Where the interval is wide, the correct conclusion is that the study was underpowered, not that the groups are equal.

For proportions instead of means, reach for the two-proportion z-test; for two measurements on the same subjects, for the paired t-test.

Running Both Versions in Python

python
import numpy as np
from scipy import stats

def two_sample_t_test(group1, group2, alpha=0.05, equal_var=False):
    n1, n2 = len(group1), len(group2)
    x1, x2 = group1.mean(), group2.mean()
    s1, s2 = group1.std(ddof=1), group2.std(ddof=1)

    t_stat, p_value = stats.ttest_ind(group1, group2, equal_var=equal_var)

    if not equal_var:                                  # Welch-Satterthwaite df
        num = (s1**2/n1 + s2**2/n2)**2
        denom = (s1**2/n1)**2/(n1-1) + (s2**2/n2)**2/(n2-1)
        df = num / denom
    else:
        df = n1 + n2 - 2

    se_diff = np.sqrt(s1**2/n1 + s2**2/n2)
    t_crit = stats.t.ppf(1 - alpha/2, df=df)
    diff = x1 - x2
    ci = (diff - t_crit * se_diff, diff + t_crit * se_diff)

    sp = np.sqrt(((n1-1)*s1**2 + (n2-1)*s2**2) / (n1+n2-2))
    d = diff / sp
    g = d * (1 - 3 / (4*(n1+n2-2) - 1))               # Hedges' g

    name = "Welch's" if not equal_var else "Pooled"
    print(f"=== {name} Two-Sample T-Test ===")
    print(f"Group 1: n={n1}, mean={x1:.2f}, sd={s1:.2f}")
    print(f"Group 2: n={n2}, mean={x2:.2f}, sd={s2:.2f}")
    print(f"t({df:.2f}) = {t_stat:.4f}, p = {p_value:.4f}")
    print(f"95% CI for mu1-mu2: ({ci[0]:.2f}, {ci[1]:.2f})")
    print(f"Cohen's d = {d:.4f}, Hedges' g = {g:.4f}")
    print(f"Decision: {'Reject H0' if p_value < alpha else 'Fail to reject H0'}")
    return t_stat, p_value, ci, d

# Summary-statistic version of the worked example
rng = np.random.default_rng(0)
a = rng.normal(78.4, 8.2, 10)
b = rng.normal(73.1, 7.5, 12)
two_sample_t_test(a, b, equal_var=False)
two_sample_t_test(a, b, equal_var=True)

# Permutation test: no distributional assumption at all
obs = a.mean() - b.mean()
pooled = np.concatenate([a, b])
perm = np.array([(rng.permutation(pooled)[:10].mean() -
                  rng.permutation(pooled)[10:].mean()) for _ in range(9999)])
p_perm = (np.abs(perm) >= abs(obs)).mean()
print(f"Permutation p-value: {p_perm:.4f}")
a <- c(80.1, 74.3, 85.6, 77.2, 79.9, 71.8, 83.4, 76.5, 82.0, 74.9)
b <- c(70.4, 75.1, 68.9, 73.6, 77.2, 71.5, 74.8, 72.0, 76.4, 70.2, 75.9, 73.3)

t.test(a, b, var.equal = FALSE)   # Welch: R's default
t.test(a, b, var.equal = TRUE)    # pooled

# Effect size with an interval, using the effectsize package
effectsize::cohens_d(a, b)
car::leveneTest(c(a, b), factor(rep(c("A", "B"), c(length(a), length(b)))))

Choosing the Right Procedure

Question you haveTestNotes
Do two independent means differ, variances unequal or unknownWelch t-testDefault choice, robust in both settings
Do two independent means differ, variance proven equalPooled t-testSlightly more powerful, rarely worth the risk
Do two matched measurements differPaired t-testUses within-subject differences
Do two independent distributions differ without normalityMann-Whitney UTests stochastic ordering, not means
Is the difference practically large enoughCohen's d with an intervalReport alongside every p-value

Common Mistakes

Running Levene's test and then picking the version of the t-test

Fix: Always use Welch. The two-stage rule inflates the overall Type I error rate and buys no power you can rely on.

Applying the independent test to repeated measurements

Fix: If each subject appears in both conditions, differences are correlated and you must use the paired t-test.

Reading a non-significant p-value as proof of no difference

Fix: Report the confidence interval for the mean difference; a wide interval means the study was underpowered, not that the groups match.

Quoting a p-value with no effect size

Fix: Give Cohen's d or Hedges' g with the raw difference, so the reader can judge practical importance.

Best Practices

  • Report t, the Welch degrees of freedom, p, the confidence interval and Cohen's d in a single sentence
  • Check the group sizes and standard deviations before anything else, since unequal n with unequal variances is the dangerous combination
  • Pre-specify whether the comparison is one- or two-sided; switching after seeing the data invalidates the p-value
  • Plot the two distributions, not just two bars, so outliers and skew are visible

Key Takeaways

  • Welch's t-test is the default: it is valid under equal variances and remains valid when they are not
  • The pooled version uses a degrees-of-freedom weighted average variance and needs n1 plus n2 minus 2 degrees of freedom
  • Welch's degrees of freedom come from the Satterthwaite formula and are usually fractional
  • Report the 95 percent confidence interval for the difference, not just the p-value
  • Cohen's d standardises the mean difference by the pooled standard deviation: 0.2 small, 0.5 medium, 0.8 large

Interview Questions

Q1: Why is Welch's test preferred over the pooled test?

Because it does not assume a common variance. Under equal variances it loses almost nothing in power, and under unequal variances the pooled test can report Type I error rates well above the nominal level, especially when the group with the larger variance is also the smaller group.

Q2: What does the Welch-Satterthwaite degrees of freedom formula do?

It computes an effective degrees of freedom from the two component variances s1 squared over n1 and s2 squared over n2. It approaches n1 plus n2 minus 2 when the variances are equal and shrinks toward the smaller group's df when they are very different.

Q3: How do you tell a paired design from an independent one?

Ask whether any unit appears in both conditions. Matching by subject, site, or time period makes the measurements dependent, so the analysis must run on within-unit differences. Treating paired data as independent discards the pairing and usually inflates the standard error.

Q4: What is the difference between statistical and practical significance here?

The p-value addresses whether the data are compatible with a zero difference, and it grows with sample size. Cohen's d and the confidence interval for the mean difference address magnitude: a tiny d can be highly significant at n = 5000 yet not worth acting on.

Frequently Asked Questions

Which version does each software package run by default?

R's t.test uses Welch unless you pass var.equal = TRUE. SciPy's ttest_ind defaults to equal_var=True, which is the pooled version, so pass equal_var=False to get Welch. Pingouin's ttest reports Welch by default as well. These defaults are a frequent source of irreproducible p-values when a Python analysis is re-run in R.

How small can a group be before the test fails?

There is no hard threshold, but with fewer than about 15 observations per group the normality assumption starts to bite, particularly with skewed outcomes. Below roughly 8 observations per group the t-test is unreliable enough that a permutation test or an exact method is preferable.

What if the variances are unequal and the sample sizes are very unbalanced?

This is the worst case for the pooled test. If the smaller group carries the larger variance, the pooled standard error is understated and the false positive rate can double or more. Welch handles it correctly, which is one more reason to never opt out of Welch deliberately.

Can I use this test on proportions or counts?

No. Means of binary or count outcomes are bounded and their sampling distributions are discrete, so the t reference distribution is wrong. Use the two-proportion z-test for conversion rates, the chi-square test for contingency tables, or a Poisson or negative binomial regression for counts.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Statistics Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement