ZetCode

R hypothesis testing

last modified November 19, 2026

A hypothesis test compares an observed sample with a claim about the population it came from. The claim, called the null hypothesis, is usually a statement of no difference or no effect. The test computes a statistic, converts it into a p-value, and the p-value is compared with a significance level chosen before the data are seen. R returns every test as an object of class htest, so the printed layout is the same whether the test is a t-test, a chi-square test, or a rank test. This article covers one-sample and two-sample t-tests, paired tests, chi-square tests, the Wilcoxon test, and the checks that decide which test is appropriate.

A one-sample t-test

The one-sample t-test asks whether the mean of a sample differs from a hypothesised value. The function t.test takes the sample and the hypothesised mean as mu. The output reports the statistic, the degrees of freedom, the p-value, a confidence interval for the mean, and the observed mean.

one-sample.R
scores <- c(72, 68, 75, 70, 66, 74, 71, 69, 73, 67)
n <- length(scores)
se <- sd(scores) / sqrt(n)
cat("n:", n, "\n")
cat("mean:", mean(scores), "\n")
cat("standard error:", se, "\n")
cat("t statistic:", (mean(scores) - 70) / se, "\n")
print(t.test(scores, mu = 70))

The sample mean is 70.5 against a claim of 70, and the standard error of the mean is 0.957. Dividing the half-point difference by the standard error reproduces the test statistic of 0.52. With nine degrees of freedom the p-value is 0.614, so a difference this large or larger would occur about sixty-one percent of the time if the true mean were 70. The confidence interval runs from 68.33 to 72.67 and contains the hypothesised value, which is the same conclusion expressed as an interval. The p-value is not the probability that the null hypothesis is true.

$ Rscript one-sample.R
n: 10 
mean: 70.5 
standard error: 0.9574271 
t statistic: 0.522233 

	One Sample t-test

data:  scores
t = 0.52223, df = 9, p-value = 0.6141
alternative hypothesis: true mean is not equal to 70
95 percent confidence interval:
 68.33415 72.66585
sample estimates:
mean of x 
     70.5 

Two independent samples

When two groups are unrelated, t.test receives both vectors and compares their means. The default is Welch's test, which does not assume that the two populations have the same variance. It adjusts the degrees of freedom to a non-integer value, which is why the df in the output is 12.203 rather than a whole number.

two-sample.R
method_a <- c(78, 82, 85, 80, 76, 88, 84, 79)
method_b <- c(70, 74, 68, 72, 76, 71, 69, 73)
print(t.test(method_a, method_b))

Method A averages 81.5 points and method B averages 71.625, a difference of about 9.9 points. The statistic is 5.81 with a p-value of 7.8e-05, so the difference is unlikely to be a product of sampling noise. The confidence interval for the difference runs from 6.18 to 13.57 points and does not contain zero. Passing var.equal = TRUE performs the pooled Student test instead, which is appropriate only when the variances really are equal.

$ Rscript two-sample.R

	Welch Two Sample t-test

data:  method_a and method_b
t = 5.8082, df = 12.203, p-value = 7.829e-05
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
  6.17743 13.57257
sample estimates:
mean of x mean of y 
   81.500    71.625 

Paired samples

A paired test is used when each observation in one group is matched with one observation in the other, such as a before and after measurement on the same person. Setting paired = TRUE reduces the data to the differences within each pair and tests whether their mean is zero. Pairing removes the variation between subjects, which usually makes the test more sensitive.

paired.R
before <- c(62, 58, 71, 65, 60, 68, 55, 66)
after <- c(70, 63, 78, 69, 66, 74, 60, 71)
print(t.test(before, after, paired = TRUE))

Every student improved, and the mean gain is 5.75 points. The statistic is negative because the test subtracts the after value from the before value, so the mean difference is -5.75. The p-value of 4.4e-06 is far below any usual threshold, and the confidence interval from -6.82 to -4.68 excludes zero. Treating these as two independent samples would ignore the matching and report a much weaker result.

$ Rscript paired.R

	Paired t-test

data:  before and after
t = -12.689, df = 7, p-value = 4.369e-06
alternative hypothesis: true mean difference is not equal to 0
95 percent confidence interval:
 -6.821561 -4.678439
sample estimates:
mean difference 
          -5.75 

Chi-square goodness of fit

The chi-square goodness-of-fit test compares observed counts with the counts expected under a hypothesised distribution. With no probabilities given, chisq.test assumes that every category is equally likely. The statistic is the sum of the squared differences between observed and expected counts, divided by the expected counts.

goodness.R
counts <- c(18, 22, 25, 15, 20)
print(counts)
print(chisq.test(counts))

The counts are 18, 22, 25, 15, and 20, and the expected count under equal preference is 20 in each category. The statistic is 2.9 with four degrees of freedom, one less than the number of categories, and the p-value is 0.575. There is no evidence that the categories are preferred unequally. The test works on counts, so the input must not be a proportion or an average.

$ Rscript goodness.R
[1] 18 22 25 15 20

	Chi-squared test for given probabilities

data:  counts
X-squared = 2.9, df = 4, p-value = 0.5747

Chi-square independence

A contingency table crosses two categorical variables. The chi-square test of independence asks whether the distribution of one variable depends on the other. The degrees of freedom are the number of rows minus one, multiplied by the number of columns minus one.

independence.R
grades <- matrix(c(18, 12, 10, 8, 22, 30), nrow = 2, byrow = TRUE,
                 dimnames = list(c("math", "art"), c("A", "B", "C")))
print(grades)
print(chisq.test(grades))

The table has two rows and three columns, so there are two degrees of freedom. The statistic of 13.32 gives a p-value of 0.0013, which is evidence that the grade distribution differs between the subjects. Mathematics has more A grades than the independence model expects, and art has more C grades. The test says that the variables are associated, not which cells cause the association; standardised residuals answer that question.

$ Rscript independence.R
      A  B  C
math 18 12 10
art   8 22 30

	Pearson's Chi-squared test

data:  grades
X-squared = 13.32, df = 2, p-value = 0.001281

The Wilcoxon rank-sum test

The Wilcoxon rank-sum test compares two groups without assuming that the data are normal. It ranks all observations together and asks whether one group tends to receive higher ranks. The test is robust to outliers, because a very large value receives the top rank but does not dominate the statistic the way it dominates a mean.

wilcox.R
new <- c(18, 21, 24, 27, 90)
old <- c(10, 12, 14, 16, 19)
print(wilcox.test(new, old))

The new group contains an outlier of 90, which would inflate its mean considerably. Four of the five new values exceed every old value, so the ranks separate almost completely, and the exact p-value is 0.0159. The output says exact test because the sample is small and has no ties; with ties R switches to a normal approximation and prints a warning unless exact = FALSE is set explicitly. The test compares distributions, so a significant result does not by itself prove that the medians differ.

$ Rscript wilcox.R

	Wilcoxon rank sum exact test

data:  new and old
W = 24, p-value = 0.01587
alternative hypothesis: true location shift is not equal to 0

Checking assumptions

The t-test assumes roughly normal data and, for the pooled version, equal variances. shapiro.test checks normality and var.test compares two variances. Both are themselves hypothesis tests, so a large p-value means only that the data are compatible with the assumption, not that the assumption is proven.

assumptions.R
set.seed(7)
a <- rnorm(30, mean = 70, sd = 8)
b <- rnorm(30, mean = 74, sd = 12)
print(shapiro.test(a))
print(var.test(a, b))

The normality test on the first sample gives a p-value of 0.30, and the variance test gives 0.74, so neither check finds a problem. The samples are simulated from normal distributions with standard deviations 8 and 12, and the estimated ratio of variances is 0.88 with an interval that includes one. The seed is fixed so the output is reproducible. A Shapiro p-value below 0.05 would suggest non-normality, but with thirty observations the test has little power against mild departures.

$ Rscript assumptions.R

	Shapiro-Wilk normality test

data:  a
W = 0.95946, p-value = 0.3001


	F test to compare two variances

data:  a and b
F = 0.88446, num df = 29, denom df = 29, p-value = 0.7432
alternative hypothesis: true ratio of variances is not equal to 1
95 percent confidence interval:
 0.4209695 1.8582365
sample estimates:
ratio of variances 
         0.8844551 

A complete example

The final script compares a control group with a treatment group. It checks normality in both groups, compares their variances, and then runs the two-sample t-test. The decision to use the t-test is made from the checks rather than assumed, and the report states the difference, its interval, and the p-value.

report.R
control <- c(71, 68, 74, 66, 70, 73, 69, 72, 67, 75)
treatment <- c(76, 79, 72, 81, 77, 74, 80, 78, 75, 82)
cat("n:", length(control), "and", length(treatment), "\n")
print(shapiro.test(control))
print(shapiro.test(treatment))
print(var.test(control, treatment))
result <- t.test(treatment, control)
cat("difference:", round(diff(result$estimate), 2), "\n")
cat("p-value:", round(result$p.value, 5), "\n")
print(result$conf.int)

Both normality tests return p-values well above 0.05, and the variance ratio of 0.89 is compatible with equal variances, so the usual two-sample comparison is appropriate. The treatment group averages 6.9 points more than the control group, with a confidence interval from 3.97 to 9.83 points and a p-value printed as 1e-04 after rounding to five decimals. The interval excludes zero, so the difference is statistically significant at the five percent level. The script prints the interval for treatment minus control, which is why both bounds are positive.

$ Rscript report.R
n: 10 and 10 

	Shapiro-Wilk normality test

data:  control
W = 0.97016, p-value = 0.8924


	Shapiro-Wilk normality test

data:  treatment
W = 0.98088, p-value = 0.9697


	F test to compare two variances

data:  control and treatment
F = 0.89286, num df = 9, denom df = 9, p-value = 0.8687
alternative hypothesis: true ratio of variances is not equal to 1
95 percent confidence interval:
 0.2217731 3.5946376
sample estimates:
ratio of variances 
         0.8928571 

difference: -6.9 
p-value: 1e-04 
[1] 3.970569 9.829431
attr(,"conf.level")
[1] 0.95

Next steps

The probability distributions article explains the normal and chi-square distributions behind these p-values, and the descriptive statistics article covers the summaries that should accompany every test. The correlation article tests whether two numeric variables move together, and the linear regression article extends the same logic to a model with several predictors.

Source

R documentation: t.test

R documentation: chisq.test

R documentation: wilcox.test

R documentation: shapiro.test

R documentation: var.test

In this article we have run one-sample, two-sample, and paired t-tests, and read their statistics, degrees of freedom, p-values, and confidence intervals. We tested counts with the chi-square goodness-of-fit and independence tests, compared two groups with the Wilcoxon rank-sum test, and checked normality and equal variances before choosing a test. The final example combined the checks into a small analysis report. The series continues with R correlation.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.