Two-Sample t-Tests in Python and R
You'll learn how to run two-sample t-tests programmatically and interpret the software output.
Now that you understand the theory behind two-sample t-tests—comparing means from independent groups, choosing between pooled and Welch's approaches, and calculating test statistics—it's time to let software do the heavy lifting.
Python: Using scipy.stats.ttest_ind
Python's scipy.stats module provides ttest_ind() for independent two-sample tests:
from scipy.stats import ttest_ind
# Sample data: two groups
group1 = [23, 25, 27, 29, 31]
group2 = [18, 20, 22, 24, 26]
# Welch's t-test (unequal variances, default)
statistic, p_value = ttest_ind(group1, group2, equal_var=False)
print(f"t-statistic: {statistic:.3f}")
print(f"p-value: {p_value:.3f}")
# Pooled variance t-test
statistic_pooled, p_pooled = ttest_ind(group1, group2, equal_var=True)
print(f"Pooled t-statistic: {statistic_pooled:.3f}")
Set equal_var=False for Welch's test (safer default) or equal_var=True for the pooled approach.
R: Using t.test()
R's t.test() is equally straightforward:
group1 <- c(23, 25, 27, 29, 31)
group2 <- c(18, 20, 22, 24, 26)
# Welch's t-test (default)
result <- t.test(group1, group2, var.equal = FALSE)
print(result)
# Pooled variance t-test
result_pooled <- t.test(group1, group2, var.equal = TRUE)
Interpreting Output
Both functions return the t-statistic and p-value. Compare the p-value to your significance level (α) to decide whether to reject the null hypothesis of equal means. R's output also includes confidence intervals and degrees of freedom.
Key Takeaway: Use scipy.stats.ttest_ind() in Python or t.test() in R to quickly perform two-sample t-tests; specify the variance assumption with equal_var or var.equal parameters, then interpret the p-value against your chosen α level.