How to Run a t-Test in R

· 2 min read · Updated March 15, 2026 · beginner
r statistics t-test hypothesis-testing inference

The t-test is a fundamental statistical test for comparing means. R provides the t.test() function from the stats package for all common t-test variations.

One-Sample t-Test

Test whether a sample mean differs from a known or hypothesised value:

# Test if sample mean differs from 50
x <- c(48, 52, 55, 49, 51, 53, 47, 50, 54, 52)
result <- t.test(x, mu = 50)

print(result)
# 
# 	One Sample t-test
# 
# data:  x
# t = 0.63246, df = 9, p-value = 0.5435
# alternative hypothesis: true mean is not equal to 50
# 95 percent confidence interval:
#  48.65051 52.34949
# sample estimates:
# mean of x 
#        50.1 

Two-Sample t-Test (Independent)

Compare means from two independent groups:

# Two independent samples
group1 <- c(18, 20, 21, 19, 22, 20, 18, 21)
group2 <- c(24, 26, 25, 23, 27, 25, 24, 26)

# Traditional interface
t.test(group1, group2)

# Formula interface (preferred)
df <- data.frame(
  value = c(group1, group2),
  group = c(rep("A", 8), rep("B", 8))
)
t.test(value ~ group, data = df)

By default, R performs Welchs t-test (unequal variances). For Students t-test (equal variances), add var.equal = TRUE:

t.test(value ~ group, data = df, var.equal = TRUE)

Paired t-Test

Compare means from paired observations (before/after, matched pairs):

# Paired data: before and after treatment
before <- c(120, 118, 122, 119, 121, 117, 120, 123)
after <- c(110, 112, 108, 111, 109, 113, 110, 107)

# Paired t-test
t.test(before, after, paired = TRUE)

# Equivalent formula syntax
t.test(Pair(before, after) ~ 1)

Extracting Results Programmatically

Use the broom package to tidy results for further analysis:

library(broom)

result <- t.test(group1, group2)
tidy_result <- tidy(result)

# Extract specific values
tidy_result$estimate        # Difference in means
tidy_result$p.value         # P-value
tidy_result$conf.low        # CI lower bound
tidy_result$conf.high       # CI upper bound

See Also