How to Run t-Tests in R with t.test()
To run t-tests in R, use the t.test() function for one-sample, two-sample, and paired comparisons of means. It returns p-values, confidence intervals, and test statistics in a single call. Always check the normality assumption with shapiro.test() or a Q-Q plot before interpreting results, especially with small sample sizes.
# One-sample: test if mean differs from 50
x <- c(48, 52, 55, 49, 51, 53, 47, 50, 54, 52)
t.test(x, mu = 50)
Two-sample tests compare independent groups. Use the formula interface t.test(value ~ group, data = df) or pass two vectors directly. By default R uses Welch’s t-test (unequal variances); add var.equal = TRUE for Student’s t-test that assumes equal variances. Welch’s test is usually preferred since it does not rely on equal group variances.
# Two-sample with formula interface
group1 <- c(18, 20, 21, 19, 22, 20, 18, 21)
group2 <- c(24, 26, 25, 23, 27, 25, 24, 26)
df <- data.frame(value = c(group1, group2), group = rep(c("A", "B"), each = 8))
t.test(value ~ group, data = df)
For paired observations (before/after), set paired = TRUE. Extract tidy results with the broom package: library(broom); tidy(result) returns a data frame with estimate, p-value, and confidence bounds. Paired tests account for the correlation between repeated measurements on the same subjects.
# Paired t-test
before <- c(120, 118, 122, 119, 121, 117, 120, 123)
after <- c(110, 112, 108, 111, 109, 113, 110, 107)
t.test(before, after, paired = TRUE)
A p-value below 0.05 is evidence against the null hypothesis, not proof of the alternative. The confidence interval gives a range of plausible values for the true difference. For non-normal data or small samples that violate assumptions, the Wilcoxon test (wilcox.test()) provides a distribution-free alternative.
See also
- group_by() / summarise(), data grouping for summary stats
- mean(), calculate sample means