D, p, q, and r functions
Section of Probability and simulation in R, part of Using R
D, p, q, and r functions
| Type | Section |
| Taught in | Probability and simulation in R |
| Part | Using R |
For a family that R names, four functions share the stem.
| Letter | What it returns | Continuous case |
|---|---|---|
d |
density or mass at a point | a density, not a probability |
p |
cumulative probability \mathrm{P}(X\le x) | an interval probability is a difference of these |
q |
the quantile, inverting p |
inverts the cumulative probability, not the density height |
r |
independent draws | one call of size n is a sample, not a loop |
c(
mass_at_3 = dbinom(3, size = 10, prob = 0.4),
probability_at_most_3 = pbinom(3, size = 10, prob = 0.4),
ninetieth_percentile = qbinom(0.9, size = 10, prob = 0.4)
)
set.seed(1)
rbinom(6, size = 10, prob = 0.4)dbinom(3, size = 10, prob = 0.4) is \binom{10}{3}(0.4)^3(0.6)^7, the mass at exactly three successes. pbinom sums that mass from zero up to three. qbinom(0.9, size = 10, prob = 0.4) is the smallest integer whose cumulative probability is at least 0.9. rbinom draws six independent binomials. The seed makes the six draws repeatable. It does not make them a population.
dnorm(0) is the standard normal density at zero, \phi(0) = 1/\sqrt{2\pi}, about 0.399. It is not the probability of observing exactly zero. A continuous distribution assigns probability zero to a single point. An interval probability is a difference of distribution functions:
c(density_at_0 = dnorm(0),
probability_within_1.96 = pnorm(1.96) - pnorm(-1.96))The second value is the probability that a standard normal draw falls in [-1.96, 1.96], about 0.95. qnorm(0.975) is the point that puts probability 0.975 to its left. Using dnorm where a probability is required, or qnorm where a density height is required, produces a number with the wrong unit.
The same four letters apply to every family R ships: dpois, pbeta, qgamma, rt, rf, rchisq. The parameterisation has to match the page that states the law. For the gamma, dgamma(x, shape, rate) uses a rate, which is the parameterisation on the distribution sheet. scale is the reciprocal of rate, and passing one where the other was intended multiplies the mean by the wrong factor.