Sunday, November 8, 2026

Understanding the Shapiro-Wilk Test: Normality, the W Statistic, R Implementation, Confidence Intervals, and Tests for Other Distributions

Many familiar statistical procedures begin with an assumption that is easy to write down but surprisingly subtle to check:

X ~ N(μ, σ2)

In words, we assume that the observations, errors, or residuals come from a normal distribution.

The Shapiro-Wilk test is one of the most widely used formal tests of this assumption. It asks:

If these observations really came from a normal distribution, would their ordered values look approximately the way ordered observations from a normal distribution should look?

Behind that simple question sits an elegant statistic called W.

1. Why test for normality?

The normal distribution appears throughout classical statistics, including:

  • one-sample t-tests;
  • two-sample t-tests;
  • analysis of variance;
  • linear regression;
  • confidence intervals for means;
  • many parametric statistical models.

However, an important distinction is often missed. In regression and ANOVA, we generally do not require the raw response variable itself to be normally distributed. Instead, the assumption usually concerns the errors or residuals.

For example:

Yi = β0 + β1Xi + εi

with the assumption:

εi ~ N(0, σ2)

Therefore, applying shapiro.test() mechanically to every raw variable in a dataset is usually not good statistical practice.

2. A brief history of the Shapiro-Wilk test

The test was introduced by Samuel S. Shapiro and Martin B. Wilk in 1965 in their influential paper:

Shapiro SS, Wilk MB. An analysis of variance test for normality (complete samples). Biometrika. 1965;52(3-4):591-611.

The test became popular because it showed strong power against many forms of non-normality.

Later, Patrick Royston developed computational approximations that allowed the test to be applied efficiently to larger datasets. Modern statistical software, including R, uses algorithms derived from this work.

3. The hypotheses

The null hypothesis is:

H0: The sample is drawn from a normal distribution.

The alternative hypothesis is:

HA: The sample is not drawn from a normal distribution.

Notice that the test does not ask whether the mean is zero or whether the variance is one. It tests the shape of the distribution.

For example, all of the following are normal distributions:

N(0,1)
N(100,25)
N(-500,10000)

4. The Shapiro-Wilk statistic

Suppose we observe:

x1, x2, ..., xn

First arrange them in ascending order:

x(1) ≤ x(2) ≤ ... ≤ x(n)

The Shapiro-Wilk statistic is:

W = [( Σi=1n aix(i) )2] / [ Σi=1n (xi - x̄)2 ]

where:

  • x(i) is the i-th ordered observation;
  • x̄ is the sample mean;
  • ai are special coefficients derived from expected order statistics of a normal distribution.

5. What are the ai coefficients?

Imagine repeatedly drawing samples of size n from a standard normal distribution:

N(0,1)

For each sample, sort the observations. After many repetitions, we can determine the expected smallest value, expected second-smallest value, and so forth.

These are called expected normal order statistics.

The Shapiro-Wilk coefficients are constructed from these expected order statistics and their covariance structure.

Conceptually, the test compares:

the pattern of the ordered observed data

with:

the pattern expected if the data truly came from a normal distribution.

6. Understanding the numerator

The numerator is:

( Σ aix(i) )2

It measures how strongly the ordered observations agree with the ordering expected under normality.

Departures such as the following tend to reduce this agreement:

  • strong skewness;
  • heavy tails;
  • extreme outliers;
  • multimodality;
  • truncation.

7. Understanding the denominator

The denominator is:

Σ(xi - x̄)2

This is simply the total variability around the sample mean.

Recall:

s2 = Σ(xi - x̄)2 / (n - 1)

Therefore:

Σ(xi - x̄)2 = (n - 1)s2

8. How should W be interpreted?

Values of W close to 1 indicate that the ordering of the observations closely resembles what would be expected under a normal distribution.

W ≈ 1    →    data are highly compatible with normality

Smaller values indicate stronger deviations from normality.

However, there is no universal cutoff such as:

W < 0.95 means the data are non-normal.

The null distribution of W depends on sample size. This is why the p-value is used.

9. Running the Shapiro-Wilk test in R

# Make the simulation reproducible
set.seed(123)

# Generate 30 observations from a normal distribution
x <- rnorm(
  n = 30,
  mean = 50,
  sd = 10
)

# Perform the Shapiro-Wilk test
shapiro.test(x)

A typical output is:

Shapiro-Wilk normality test

data:  x
W = 0.97...
p-value = 0....

10. Interpreting the p-value

Suppose:

W = 0.976
p-value = 0.72

Using:

α = 0.05

we have:

p > 0.05

We therefore fail to reject the null hypothesis.

A suitable interpretation is:

There is insufficient evidence to conclude that the data depart from normality.

Avoid saying:

The data are normally distributed.

A non-significant test does not prove that the population is normal.

11. Example with clearly non-normal data

set.seed(123)

# Generate right-skewed exponential data
x_exp <- rexp(
  n = 50,
  rate = 1
)

# Test normality
shapiro.test(x_exp)

Because the exponential distribution is strongly right-skewed, the test will generally return a smaller W and a small p-value.

12. Always inspect a Q-Q plot

qqnorm(x)
qqline(x)

A normal Q-Q plot compares the observed sample quantiles with theoretical normal quantiles.

If the data are approximately normal, the points should lie close to a straight line.

13. Why sample size matters

Small samples

With a sample such as n = 8, even fairly substantial departures from normality may not be detected because the test has limited power.

Large samples

With a sample such as n = 2000, tiny departures from perfect normality can produce extremely small p-values.

Therefore:

Statistical evidence against exact normality does not automatically mean that a parametric statistical method is inappropriate.

14. Demonstrating sample-size effects in R

set.seed(100)

# Slightly skewed distribution
small_sample <- rgamma(
  20,
  shape = 20,
  rate = 1
)

large_sample <- rgamma(
  2000,
  shape = 20,
  rate = 1
)

shapiro.test(small_sample)

shapiro.test(large_sample)

Both samples come from the same non-normal population, but the larger sample has much greater power to detect the deviation.

15. Understanding the d, p, q and r functions in R

Most probability distributions in R have four related functions:

Prefix Meaning Normal example
d Density or probability mass dnorm()
p Cumulative probability pnorm()
q Quantile qnorm()
r Random generation rnorm()

The Shapiro-Wilk test itself does not have standard Base R functions named:

dshapiro()
pshapiro()
qshapiro()
rshapiro()

Instead, shapiro.test() internally calculates W and its p-value.

16. dnorm(): the normal density

The normal probability density function is:

f(x) = [1 / (σ√(2π))] × exp[-(x - μ)2 / (2σ2)]

In R:

dnorm(
  0,
  mean = 0,
  sd = 1
)

This gives approximately:

0.3989423

This value is a density, not the probability that X equals zero.

For a continuous distribution:

P(X = 0) = 0

17. Writing our own dnorm()

my_dnorm <- function(x, mean = 0, sd = 1) {

  # Standard deviation must be positive
  if (sd <= 0)
    stop("sd must be greater than zero")

  # Standardise x
  z <- (x - mean) / sd

  # Normal probability density
  density <-
    (1 / (sd * sqrt(2 * pi))) *
    exp(-0.5 * z^2)

  return(density)
}

Compare with Base R:

my_dnorm(0)
dnorm(0)

my_dnorm(
  10,
  mean = 5,
  sd = 2
)

dnorm(
  10,
  mean = 5,
  sd = 2
)

18. pnorm(): cumulative probability

The cumulative distribution function is:

F(x) = P(X ≤ x)

For example:

pnorm(1.96)

returns approximately:

0.975

Therefore:

P(Z ≤ 1.96) ≈ 0.975

Similarly:

pnorm(-1.96)

is approximately:

0.025

Hence:

P(-1.96 < Z < 1.96) ≈ 0.95

In R:

pnorm(1.96) - pnorm(-1.96)

19. Writing our own pnorm()

The normal cumulative distribution function does not have a simple elementary antiderivative, but it can be calculated numerically.

my_pnorm_one <- function(q, mean = 0, sd = 1) {

  if (sd <= 0)
    stop("sd must be greater than zero")

  answer <- integrate(
    f = function(x) {
      my_dnorm(
        x,
        mean = mean,
        sd = sd
      )
    },
    lower = -Inf,
    upper = q
  )

  return(answer$value)
}

Test it:

my_pnorm_one(1.96)
pnorm(1.96)

A vectorised version:

my_pnorm <- function(q, mean = 0, sd = 1) {

  sapply(
    q,
    my_pnorm_one,
    mean = mean,
    sd = sd
  )
}

20. qnorm(): the quantile function

The quantile function performs the reverse operation of the CDF.

For example:

qnorm(0.975)

returns approximately:

1.96

In mathematical terms:

F-1(0.975) ≈ 1.96

21. Writing our own qnorm()

my_qnorm_one <- function(
  p,
  mean = 0,
  sd = 1
) {

  if (p <= 0 || p >= 1)
    stop("p must lie strictly between 0 and 1")

  if (sd <= 0)
    stop("sd must be greater than zero")

  objective <- function(x) {

    my_pnorm_one(
      x,
      mean = mean,
      sd = sd
    ) - p
  }

  lower <- mean - 10 * sd
  upper <- mean + 10 * sd

  root <- uniroot(
    objective,
    interval = c(lower, upper)
  )

  return(root$root)
}

Compare:

my_qnorm_one(0.975)
qnorm(0.975)

22. rnorm(): generating normal random variables

Base R generates random normal observations using:

rnorm(10)

or:

rnorm(
  n = 100,
  mean = 50,
  sd = 10
)

A classical way to generate normally distributed values is the Box-Muller transformation.

Suppose U1 and U2 are independent Uniform(0,1) random variables.

Then:

Z1 = √[-2 ln(U1)] cos(2πU2)
Z2 = √[-2 ln(U1)] sin(2πU2)

Both Z1 and Z2 follow the standard normal distribution.

23. Writing our own rnorm() using Box-Muller

my_rnorm <- function(
  n,
  mean = 0,
  sd = 1
) {

  if (n < 1)
    return(numeric(0))

  if (sd < 0)
    stop("sd must be non-negative")

  # Box-Muller generates values in pairs
  m <- ceiling(n / 2)

  # Generate independent uniforms
  u1 <- runif(m)
  u2 <- runif(m)

  # Protect against log(0)
  u1[u1 == 0] <-
    .Machine$double.xmin

  # Box-Muller transformation
  z1 <-
    sqrt(-2 * log(u1)) *
    cos(2 * pi * u2)

  z2 <-
    sqrt(-2 * log(u1)) *
    sin(2 * pi * u2)

  # Combine
  z <- c(z1, z2)

  # Keep requested number
  z <- z[seq_len(n)]

  # Convert to N(mean, sd^2)
  x <- mean + sd * z

  return(x)
}

Test it:

set.seed(42)

x <- my_rnorm(
  n = 10000,
  mean = 50,
  sd = 10
)

mean(x)
sd(x)

24. The d-p-q-r pattern across R distributions

Distribution d p q r
Normal dnorm pnorm qnorm rnorm
Binomial dbinom pbinom qbinom rbinom
Poisson dpois ppois qpois rpois
Exponential dexp pexp qexp rexp
Gamma dgamma pgamma qgamma rgamma
Beta dbeta pbeta qbeta rbeta
Uniform dunif punif qunif runif
Weibull dweibull pweibull qweibull rweibull

25. Does the Shapiro-Wilk test have a confidence interval?

Normally, no.

shapiro.test() returns:

  • the W statistic;
  • a p-value;
  • the test name;
  • the data name.

It does not return a conventional confidence interval because W is a goodness-of-fit statistic rather than a simple biological parameter such as a mean or mean difference.

26. Confidence interval for the mean

If normality is reasonably plausible, a confidence interval for the population mean can be calculated using the t distribution.

x̄ ± t0.975,n-1 (s / √n)

In R:

set.seed(10)

x <- rnorm(
  30,
  mean = 100,
  sd = 15
)

n <- length(x)
xbar <- mean(x)
s <- sd(x)

alpha <- 0.05

critical_t <- qt(
  1 - alpha / 2,
  df = n - 1
)

margin <-
  critical_t *
  s / sqrt(n)

lower <- xbar - margin
upper <- xbar + margin

c(
  mean = xbar,
  lower_95 = lower,
  upper_95 = upper
)

Compare with:

t.test(x)

27. Confidence interval for the variance

For normally distributed data:

[(n - 1)S2] / σ2 ~ χ2n-1

The confidence interval for the variance is:

Lower = (n - 1)s2 / χ20.975,n-1
Upper = (n - 1)s2 / χ20.025,n-1
variance_ci <- function(
  x,
  conf.level = 0.95
) {

  x <- x[!is.na(x)]

  n <- length(x)

  if (n < 2)
    stop(
      "At least two observations are required"
    )

  s2 <- var(x)

  alpha <- 1 - conf.level
  df <- n - 1

  lower <-
    df * s2 /
    qchisq(
      1 - alpha / 2,
      df = df
    )

  upper <-
    df * s2 /
    qchisq(
      alpha / 2,
      df = df
    )

  return(
    c(
      variance = s2,
      lower = lower,
      upper = upper
    )
  )
}

28. Simulating the null distribution of W

A useful teaching exercise is to simulate what values of W occur when the null hypothesis is actually true.

simulate_W_null <- function(
  n,
  B = 5000
) {

  W <- numeric(B)

  for (b in seq_len(B)) {

    # Generate a sample under H0
    x <- rnorm(n)

    # Calculate W
    W[b] <-
      unname(
        shapiro.test(x)$statistic
      )
  }

  return(W)
}

Run:

set.seed(123)

W_null <- simulate_W_null(
  n = 30,
  B = 5000
)

hist(
  W_null,
  breaks = 40,
  main = "Null distribution of Shapiro-Wilk W",
  xlab = "W"
)

This demonstrates why the same W value cannot be interpreted identically for every sample size.

29. Empirical critical value

quantile(
  W_null,
  probs = 0.05
)

This gives an approximate 5% lower-tail critical value for that particular sample size.

30. Empirical p-value

W_obs <-
  unname(
    shapiro.test(x)$statistic
  )

p_empirical <-
  (sum(W_null <= W_obs) + 1) /
  (length(W_null) + 1)

p_empirical

31. Comparable tests for normality

Shapiro-Francia test

The Shapiro-Francia test is closely related to the Shapiro-Wilk test and compares observed order statistics with expected normal order statistics.

Anderson-Darling test

The Anderson-Darling test compares an empirical distribution with a theoretical distribution and gives relatively greater weight to the tails.

Conceptually:

A2 = -n - (1/n) Σ (2i - 1) [ ln F(x(i)) + ln(1 - F(x(n+1-i))) ]

It can be adapted to normal, exponential, Weibull and other distributions.

Kolmogorov-Smirnov test

The K-S statistic is:

D = sup |Fn(x) - F0(x)|

It measures the largest vertical difference between the empirical CDF and the theoretical CDF.

Example:

x <- rnorm(50)

ks.test(
  x,
  "pnorm",
  mean = 0,
  sd = 1
)

A crucial warning: the classical K-S test assumes that the theoretical distribution and its parameters were specified independently of the data.

Cramér-von Mises test

The Cramér-von Mises approach considers the overall squared discrepancy between the empirical and theoretical cumulative distributions.

W2 = n ∫ [Fn(x) - F0(x)]2 dF0(x)

Jarque-Bera test

The Jarque-Bera test focuses on skewness and kurtosis.

JB = (n / 6) [ S2 + (K - 3)2 / 4 ]

For a normal distribution:

Skewness = 0
Kurtosis = 3

32. Testing whether data follow an exponential distribution

For:

X ~ Exponential(λ)

R provides:

dexp()
pexp()
qexp()
rexp()

Example:

set.seed(123)

x <- rexp(
  100,
  rate = 0.5
)

ks.test(
  x,
  "pexp",
  rate = 0.5
)

If the rate parameter is estimated from the same data, the ordinary K-S p-value should not be interpreted directly.

33. Parametric bootstrap for exponential goodness-of-fit

exponential_gof <- function(
  x,
  B = 5000
) {

  x <- x[!is.na(x)]

  n <- length(x)

  if (any(x < 0))
    stop(
      "Exponential observations must be non-negative"
    )

  # Maximum-likelihood estimate
  lambda_hat <- 1 / mean(x)

  # Observed KS statistic
  D_obs <-
    unname(
      ks.test(
        x,
        "pexp",
        rate = lambda_hat
      )$statistic
    )

  D_sim <- numeric(B)

  for (b in seq_len(B)) {

    # Generate under fitted null
    xb <- rexp(
      n,
      rate = lambda_hat
    )

    # Re-estimate rate
    lambda_b <- 1 / mean(xb)

    # Calculate simulated statistic
    D_sim[b] <-
      unname(
        ks.test(
          xb,
          "pexp",
          rate = lambda_b
        )$statistic
      )
  }

  p_value <-
    (sum(D_sim >= D_obs) + 1) /
    (B + 1)

  return(
    list(
      rate_estimate = lambda_hat,
      statistic = D_obs,
      p.value = p_value
    )
  )
}

34. Testing a uniform distribution

set.seed(10)

x <- runif(
  50,
  min = 0,
  max = 1
)

ks.test(
  x,
  "punif",
  min = 0,
  max = 1
)

35. Testing lognormality

A useful identity is:

X is lognormal ⇔ log(X) is normal

Therefore:

shapiro.test(
  log(x)
)

can provide a simple diagnostic for lognormality.

36. Testing Poisson data

Poisson data are discrete, so the Shapiro-Wilk test is inappropriate.

For:

X ~ Poisson(λ)

R provides:

dpois()
ppois()
qpois()
rpois()

Example:

set.seed(10)

x <- rpois(
  200,
  lambda = 3
)

lambda_hat <- mean(x)

observed <- table(x)

observed

Observed and expected frequency distributions can then be compared using chi-square or simulation-based goodness-of-fit procedures.

37. Testing binomial data

For:

X ~ Binomial(m,p)

R provides:

dbinom()
pbinom()
qbinom()
rbinom()

Observed frequencies for 0, 1, ..., m successes can be compared against the corresponding binomial probabilities.

38. Testing a Weibull distribution

The Weibull distribution is widely used in survival analysis and reliability modelling.

R provides:

dweibull()
pweibull()
qweibull()
rweibull()

The Anderson-Darling test is often particularly useful for Weibull models because tail behaviour can be scientifically important.

39. Which goodness-of-fit test should be used?

Question Useful approach
Are continuous data normal? Shapiro-Wilk + Q-Q plot
Is normal tail fit especially important? Anderson-Darling
Does an empirical CDF match a fully specified distribution? Kolmogorov-Smirnov
Want sensitivity across the whole CDF? Cramér-von Mises
Interested primarily in skewness and kurtosis? Jarque-Bera
Normal parameters estimated from the sample? Shapiro-Wilk or Lilliefors
Lognormality? Shapiro-Wilk on log(x)
Exponentiality? Anderson-Darling or bootstrap GOF
Weibull fit? Anderson-Darling or bootstrap GOF
Poisson or binomial distribution? Chi-square or simulation-based GOF
Arbitrary fitted distribution? Parametric bootstrap

40. Why histograms alone are not enough

set.seed(10)

x <- rnorm(25)

hist(x)

With small samples, changing the number of histogram bins can make the same data appear bell-shaped, skewed, bimodal or irregular.

For evaluating normality, a Q-Q plot is generally more informative.

41. Why Shapiro-Wilk alone is not enough

x <- c(
  rnorm(99),
  10
)

shapiro.test(x)

This sample will probably fail the normality test because of one extreme observation.

However, the scientifically important question may be whether that value represents:

  • a measurement error;
  • a data-entry error;
  • a genuine biological observation;
  • a different population;
  • or another source of heterogeneity.

A normality test cannot distinguish these possibilities.

42. Normality is often less important than students are taught

A common but oversimplified workflow is:

Shapiro-Wilk significant
↓
data non-normal
↓
t-test forbidden

This is not generally correct.

The t-test can be reasonably robust to moderate departures from normality, particularly when:

  • sample sizes are reasonably large;
  • group sizes are balanced;
  • there are no extreme outliers.

Conversely, obtaining p > 0.05 from a Shapiro-Wilk test with n = 6 provides very little evidence that the underlying population is actually normal.

43. The key conceptual idea

The Shapiro-Wilk test is not merely asking:

Does the histogram look bell-shaped?

Its deeper question is:

Do the ordered observations behave the way order statistics from a normal distribution should behave?

That is why the statistic is built around:

x(1), x(2), ..., x(n)

and coefficients derived from the expected order statistics of a normal distribution.

44. Final perspective

The Shapiro-Wilk statistic has the compact form:

W = [( Σ aix(i) )2] / [ Σ(xi - x̄)2 ]

But behind this formula lies a sophisticated idea: compare the geometry of the ordered observations with the geometry expected from normal order statistics.

A small W indicates disagreement. The p-value tells us how surprising that disagreement would be if normality were true.

Neither replaces looking at the data.

The strongest workflow is:

scientific context → plot the data → Q-Q plot → formal test → evaluate practical importance

The same general idea extends beyond normality. Exponential, Weibull, lognormal, Poisson, binomial and many other probability models can be evaluated by asking:

What should the observations look like under the proposed model, and how different are the observed data from that expectation?

References

  1. Shapiro SS, Wilk MB. An analysis of variance test for normality (complete samples). Biometrika. 1965;52(3-4):591-611. DOI: 10.1093/biomet/52.3-4.591.
  2. Royston JP. An extension of Shapiro and Wilk's W test for normality to large samples. Applied Statistics. 1982;31(2):115-124.
  3. Royston P. Remark AS R94: A remark on Algorithm AS 181: The W-test for normality. Applied Statistics. 1995;44(4):547-551.
  4. Stephens MA. EDF statistics for goodness of fit and some comparisons. Journal of the American Statistical Association. 1974;69:730-737.

No comments: