Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 39 ยท Statistics and Modeling

Probability Distributions in R: dnorm, pnorm, qnorm, rnorm

Master R's distribution functions: the d, p, q and r prefixes for normal, binomial, Poisson, uniform, exponential, t and chi-squared, plus sample(), set.seed() and simulation.

R ships with dozens of probability distributions, all following one naming scheme. Learn the scheme once and you can use any of them: the normal curve, coin flips, call-center arrivals, waiting times, and the t and chi-squared distributions that underlie hypothesis tests. This lesson also shows how to draw random numbers and run small simulations.

R is not available on this site, so the R code is read-only. Every numeric result shown in a comment was cross-checked with SciPy, and the Python block at the end lets you reproduce them. Randomly generated numbers are not shown, because they depend on R's random number generator and seed.

The d, p, q, r scheme

Each distribution has a base name (norm, binom, pois, unif, exp, t, chisq, ...). Put one of four letters in front:

Four prefixes, one pattern

d = density Height of the curve, or P(X = k)
p = probability Cumulative: P(X <= x)
q = quantile Inverse of p
r = random Draw n random values

dnorm, pnorm, qnorm, rnorm: same story for every distribution.

1 / 2
Prefix Question it answers Normal example
d How likely is exactly this (discrete) or how dense is the curve here (continuous)? dnorm(0)
p What is the probability of a value at or below x? pnorm(1.96)
q Which value has this cumulative probability? qnorm(0.975)
r Give me n random values. rnorm(5)

The normal distribution

The standard normal has mean 0 and standard deviation 1. Change them with the mean and sd arguments.

R
dnorm(0)                         # 0.3989423   (the peak of the bell)
pnorm(1.96)                      # 0.9750021   P(Z <= 1.96)
qnorm(0.975)                     # 1.959964    the 97.5th percentile
pnorm(1) - pnorm(-1)             # 0.6826895   within 1 sd of the mean
pnorm(1.5, mean = 1, sd = 0.5)   # 0.8413447   P(X <= 1.5) when X ~ N(1, 0.5)
pnorm(1.96, lower.tail = FALSE)  # the right tail, 1 - pnorm(1.96)

The "68-95-99.7 rule" is just pnorm(k) - pnorm(-k) for k = 1, 2, 3. The 1.96 you meet in confidence intervals is qnorm(0.975): leave 2.5 percent in each tail and you are left with the central 95 percent. p and q are inverses: qnorm(pnorm(1.2)) returns 1.2.

To draw a curve, plot the density with curve():

R
curve(dnorm(x, mean = 0, sd = 1), from = -4, to = 4)

Discrete distributions

A binomial counts successes in size independent trials, each with success probability prob.

R
dbinom(3, size = 10, prob = 0.5)              # 0.1171875  exactly 3 heads in 10 flips
pbinom(3, size = 10, prob = 0.5)              # 0.171875   3 heads or fewer
pbinom(5, 10, 0.5, lower.tail = FALSE)        # 0.3769531  more than 5 heads

The first answer is the number of ways to choose which 3 of 10 flips are heads (120) times 0.5 to the 10th power (120 / 1024). A Poisson counts events in a fixed interval when they occur at an average rate lambda:

R
dpois(2, lambda = 3)    # 0.2240418   exactly 2 events when the average is 3
ppois(2, lambda = 3)    # 0.4231901   2 or fewer

Note: for discrete distributions d gives the probability of one exact value (the mass), and p adds up everything up to and including it.

Continuous distributions

R
punif(0.3)                  # 0.3        uniform on [0, 1]
pexp(1, rate = 1)           # 0.6321206  waiting-time distribution: P(wait <= 1)
qt(0.975, df = 10)          # 2.228139   t critical value for a 95% interval
qchisq(0.95, df = 3)        # 7.814728   chi-squared critical value

For a continuous variable, dnorm() and friends return the density, which can exceed 1 for narrow distributions. A density is not a probability; areas under the curve (differences of p values) are.

Other distributions at a glance

Base name Distribution Typical use
norm normal measurement error, averages
binom binomial number of successes in n trials
pois Poisson counts of rare events
geom geometric trials until the first success
unif uniform all values equally likely
exp exponential time between events
gamma, weibull, lnorm skewed positive durations, sizes, incomes
t, chisq, f sampling distributions tests, intervals, ANOVA
beta beta probabilities, proportions

Parameter names differ per distribution: rate for exp, lambda for pois, df for t, chisq and f. Use ?Distributions to see them all.

Random numbers, seeds and sampling

r*() functions draw random values. Computers use pseudo-random generators, so set.seed() makes a script reproducible:

R
set.seed(42)
x <- rnorm(1000, mean = 50, sd = 10)    # 1000 random values
mean(x); sd(x)                          # close to 50 and 10, but not exactly

The same seed gives the same numbers every time you run the script in R; the exact values differ from Python's or Excel's generator, so do not expect to match them. Call set.seed() once at the top of a script, not inside loops.

sample() draws from your own vector:

R
sample(1:6, 1)                         # roll a die
sample(1:6, 10, replace = TRUE)        # ten rolls
sample(c("H", "T"), 5, replace = TRUE, prob = c(0.7, 0.3))   # a loaded coin
sample(nrow(mtcars), 5)                # 5 random row numbers, no repeats

Without replace = TRUE each item can be picked at most once, so sample(1:6, 10) is an error.

Simulation: seeing the law of large numbers and the CLT

Simulation turns probability questions into code. How often do 10 coin flips give 3 or fewer heads?

R
set.seed(1)
heads <- rbinom(100000, size = 10, prob = 0.5)
mean(heads <= 3)        # about 0.17, close to the exact pbinom(3, 10, 0.5) = 0.171875

The estimate wanders around the exact value, and gets closer as the number of repetitions grows (the law of large numbers). A second classic: averages of many samples are close to normal even when the data are not (the central limit theorem).

R
set.seed(1)
means <- replicate(5000, mean(rexp(30, rate = 1)))   # 5000 sample means of skewed data
hist(means, breaks = 40)                              # a bell shape around 1
sd(means)                                             # near 1 / sqrt(30), about 0.18

Exponential data are heavily skewed, but the histogram of means looks like a bell centered at 1, with a standard deviation near 1 / sqrt(30) = 0.1826. This is why the t-tests in the next lesson work for averages even with imperfect data.

Check the numbers in Python

A Python comparison for all the exact values above (SciPy has the same d/p/q functions under different names). The simulation is seeded, but will not match R's draws, only the exact answers.

Python Python comparison: exact values and a simulation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Reading dnorm() as a probability. It is a density; use pnorm() differences for probabilities.
  • Forgetting lower.tail = FALSE for "greater than" questions (or writing 1 - p and losing precision for tiny tails).
  • Using sample() without replace = TRUE for more draws than items.
  • Calling set.seed() inside a loop, which makes every iteration identical.
  • Confusing sd (standard deviation) with variance in rnorm().

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which function returns the value x such that P(Z <= x) = 0.975 for a standard normal Z?

    q functions are inverses of p functions: they map a cumulative probability to a value.
  2. 2. What does dbinom(3, size = 10, prob = 0.5) give?

    For discrete distributions d returns the probability of exactly that value.
  3. 3. How do you get P(X > 5) for X ~ Binomial(10, 0.5)?

    lower.tail = FALSE returns the upper tail P(X > 5).
  4. 4. Why call set.seed() before rnorm()?

    The same seed gives the same pseudo-random sequence, so your results can be reproduced.

Summary

  • Every distribution has d (density/mass), p (cumulative), q (quantile) and r (random) functions.
  • pnorm, qnorm, dnorm handle the normal; dbinom/pbinom, dpois/ppois, pexp, qt, qchisq cover the common others.
  • lower.tail = FALSE gives upper tails.
  • set.seed() makes simulations reproducible; sample(), rbinom() and replicate() turn probability questions into code.
  • The law of large numbers and the central limit theorem explain why simulations and averages behave well.

Next: Hypothesis Tests in R