
4 Random Variables
Previously, we computed a distribution given the data, whereas now we generate individual data points given the distribution.
This chapter asks three questions.
- How do we describe data we have not seen yet?
- Random variables: a random variable \(X_{i}\) generates values from a probability distribution, and a realized value \(\hat{x}_{i}\) is one draw.
- Which distributions come up most often?
- Bernoulli, Discrete Uniform, and Multinoulli: these describe discrete outcomes with a probability mass function \(p(x)\), the theoretical analogue of the empirical mass function.
- Continuous Uniform, Exponential, and Normal: these describe continuous outcomes with a density \(f(x)\), which is like a histogram with infinite data.
- How do we compute probabilities from a distribution?
- CDF: this is the theoretical analogue of the empirical CDF, \(F(x)=\text{Prob}(X_{i} \leq x)\). The probability of landing in a range is then a difference, \(\text{Prob}(a < X_{i} \leq b)=F(b)-F(a)\).
To talk about data we have not yet observed, we need an object that names the set of possible outcomes and the long-run frequency of each.
The random-variable framing is useful for reasoning about a data generating process before any data are observed. For example, consider flipping a coin before knowing whether it lands on heads or tails. We denote the unflipped coin as the random variable \(X_{i}\), with sample space \(\{0, 1\}\) and probability \(1/2\) on each outcome. Here \(x=1\) is heads and \(x=0\) is tails. A specific flipped coin that has landed heads or tails is denoted \(\hat{x}_{i}\), mirroring the hat notation from the previous chapter.
There are two basic types of sample spaces: discrete (encompassing cardinal-discrete, factor-ordered, and factor-unordered data) and continuous. This leads to two types of random variables: discrete and continuous. However, each type has many different probability distributions. The most common random variables are easily accessible in R.
Cumulative Probability
We often want the probability that a random variable falls at or below some value \(x\).
You can think of \(F(x)\) as the ECDF for a dataset with an infinite number of observations; equivalently, the ECDF is an empirical version of the CDF applied to observed data. The CDF is useful because it packages every probability of interest into a single function, and works for both continuous random variables and ordered factors.
Probability Rules
The CDF has some basic implications. Intuitively, probabilities must sum up to one. So we can compute \(\text{Prob}(X_{i} > x) = 1- F(x)\). We also have two “in” and “out” probabilities.
The probability of \(X_{i}\leq b\) and \(X_{i}> a\) can be written in terms of falling into a range \[\text{Prob}(X_{i}~\text{in}~(a,b])=\text{Prob}(a < X_{i} \leq b) = F(b) - F(a).\] The opposite probability is \[\begin{aligned} \text{Prob}(X_{i} \text{ out of } (a,b]) &= \text{Prob}(X_{i} \leq a \text{ or } X_{i} > b) = F(a) + [1- F(b)] \\ &= 1 - [F(b) - F(a)] = 1 - \text{Prob}( X_{i}~\text{in}~(a,b]). \end{aligned}\]
The endpoints matter when \(X_{i}\) is discrete, because a single value can have positive probability. Including the left endpoint adds the probability of exactly \(a\), so \(\text{Prob}(X_{i}~\text{in}~[a,b]) = F(b) - F(a) + \text{Prob}(X_{i}=a)\). The endpoints do not matter when \(X_{i}\) is continuous (no single value has positive probability).
4.1 Discrete Random Variables
A discrete random variable can take one of several values in a set. E.g., any number in \(\{1,2,3,...\}\). With a discrete random variable, individual values can have positive probability, so we can describe the distribution by listing the probability of each value.
You can think of \(p(x)\) as a proportions bar plot for a dataset with an infinite number of observations; equivalently, the bar plot is an empirical version of the PMF applied to observed data. The CDF accumulates the mass function, \(F(x)=\sum_{x' \leq x} p(x')\), and conversely the probability of any value is the size of the jump in \(F\) at that value. The PMF is useful for reading off the probability of a particular outcome, such as rolling exactly a \(3\), and it is how you specify a discrete random variable in R.
In R, you can simulate random discrete data using the sample function. To do so, you must specify each outcome \(x\) and its probability \(p(x)\).
Code
## MAIN EXAMPLE
x <- c(0, 1)
x_probs <- c(1/2, 1/2)
sample(x, 1, prob=x_probs, replace=TRUE) # One Flip
## [1] 0
sample(x, 1, prob=x_probs, replace=TRUE) # Another Flip
## [1] 1
sample(x, 4, prob=x_probs, replace=TRUE) # 4 Flips
## [1] 0 0 0 0Bernoulli
The simplest random variable models a single yes/no event, like one flip of a coin. A Bernoulli random variable (Bernoulli 1713) takes two values, \(x=1\) (success/heads) with probability \(\theta\) and \(x=0\) (failure/tails) with probability \(1-\theta\); the single parameter \(\theta~\text{in}~[0,1]\) controls the probability of success.
Bernoulli variables are useful whenever an outcome is binary, such as heads or tails, success or failure, and present or absent. Many other discrete distributions are built by combining independent Bernoulli variables. Writing the distribution out in full helps fix the notation we will reuse for richer cases: \[\begin{aligned} X_{i} &~\text{in}~\{0,1\} \\ p(x) &= \begin{cases} 1-\theta & x=0 \\ \theta & x=1 \\ 0 & \text{Otherwise} \end{cases} \\ F(x) &= \begin{cases} 0 & x<0 \\ 1-\theta & x~\text{in}~[0,1) \\ 1 & x\geq 1 \end{cases} \end{aligned}\]
The theoretical mean of a Bernoulli variable works out to \(\theta\).
Here is an example of the Bernoulli distribution. While you might get all heads (or all tails) in the first few coin flips, the ratios level out to their theoretical values after many flips.
Code
## MAIN EXAMPLE
x <- c(0, 1)
x_probs <- c(3/4, 1/4)
sample(x, 1, prob=x_probs, replace=TRUE) # 1 Flip
## [1] 0
x_sim <- sample(x, 400, prob=x_probs, replace=TRUE) #400 Flips
# Plot proportions
proportions <- table(x_sim)/length(x_sim)
plot(proportions,
col=grey(0, 0.5),
xlab='Flip Outcome',
ylab='Proportion',
main=NA,
ylim=c(0,0.8))
points(c(0, 1), c(.75, .25), pch=16, col=rgb(0, 0, 1, .8)) # Theoretical values
Code
# Plot CDF
plot( ecdf(x_sim), col=grey(0, .5),
pch=16, main=NA) #Empirical
Code
#points(c(0, 1), c(.75, 1), pch=16, col='blue') # TheoreticalDiscrete Uniform
Discrete numbers with equal probability, such as a die with \(K\) sides. \[\begin{aligned} X_{i} &~\text{in}~\{1,...K\} \\ p(x) &= \begin{cases} 1/K & x~\text{in}~\{1,...K\} \\ 0 & \text{Otherwise} \end{cases} \\ F(x) &= \begin{cases} 0 & x<1 \\ 1/K & x~\text{in}~[1,2) \\ 2/K & x~\text{in}~[2,3) \\ \vdots & \\ 1 & x\geq K \end{cases} \end{aligned}\]
Code
## MAIN EXAMPLE
x <- c(1, 2, 3, 4)
x_probs <- c(1/4, 1/4, 1/4, 1/4)
# sample(x, 1, prob=x_probs, replace=TRUE) # 1 roll
x1_hat <- sample(x, 2000, prob=x_probs, replace=TRUE) # 2000 rolls
# Plot Long run proportions
proportions <- table(x1_hat)/length(x1_hat)
plot(proportions, col=grey(0, .5),
xlab='Outcome', ylab='Proportion', main=NA)
points(x, x_probs, pch=16, col=rgb(0, 0, 1, .8)) # Theoretical values
Code
# Hist w/ Theoretical Counts
# hist(x1_hat, breaks=50, border=NA, main=NA, ylab='Count')
# points(x, x_probs*length(x1_hat), pch='-')
# Alternative Plot
plot( ecdf(x1_hat), pch=16, col=grey(0, .5), main=NA)
Code
# Alternative Plot 2
#props <- table(x1_hat)
#barplot(props, ylim = c(0, 0.35), ylab = 'Proportion', xlab = 'Value')
#abline(h = 1/4, lty = 2)Note that the Discrete Uniform distribution generalizes to arbitrary sets, such as \(\{0.0, 0.25, 0.5, 0.75, 1.0\}\) instead of \(\{1,2,3,4,5\}\). We will not exploit the generalization in this book.
Multinoulli
Numbers \(1,...K\), with each outcome \(k\) having probability \(\theta_{k}\) and satisfying \(\theta_{1} + \theta_{2} + ... = 1\). \[\begin{aligned} X_{i} &~\text{in}~\{1,...K\} \\ p(x) &= \begin{cases} \theta_{1} & x=1 \\ \theta_{2} & x=2 \\ \vdots & \\ \theta_{K} & x=K \\ 0 & \text{Otherwise} \end{cases} \\ F(x) &= \begin{cases} 0 & x<1 \\ \theta_{1} & x~\text{in}~[1,2) \\ \theta_{1} + \theta_{2} & x~\text{in}~[2,3) \\ \vdots & \\ 1 & x\geq K \end{cases} \end{aligned}\]
Here is an empirical example with three outcomes
Code
## MAIN EXAMPLE
x <- c(1, 2, 3)
x_probs <- c(3/10, 1/10, 6/10)
sum(x_probs)
## [1] 1
x2_hat <- sample(x, 2000, prob=x_probs, replace=TRUE) # sample of 2000
# Plot Long run proportions
proportions <- table(x2_hat)/length(x2_hat)
plot(proportions, col=grey(0, .5), ylim=c(0, 0.7),
xlab='Outcome', ylab='Proportion', main=NA)
points(seq(x), x_probs, pch=16, col=rgb(0, 0, 1, .8)) # Theoretical values
Code
# Alternative Plot
# plot( ecdf(x2_hat), pch=16, col=grey(0, .5), main=NA)We can also replace numbers with letters \((A,...Z)\) or names \((\text{John}, \text{Jamie}, ...)\) although we must be careful with the CDF when there is no longer a natural ordering. When the outcomes are not cardinal data, the Multinoulli random variable is typically referred to as a Categorical random variable. The CDF \(F(x)=\text{Prob}(X_{i} \leq x)\) requires an ordering on the outcomes. Labels like “my car dies” and “it rains next Tuesday” have no inherent order, so their CDF depends on whatever order we choose.
4.2 Continuous Random Variables
A continuous random variable can take one value out of an uncountably infinite number. E.g., any number between \(0\) and \(1\) with any number of decimal points. With a continuous random variable, the probability of any individual point is zero. So we cannot describe the distribution by listing \(\text{Prob}(X_{i} = x)\) for each \(x\). Instead, we describe it with the CDF or with a density.
The PDF is useful for intuition. Probabilities are areas under \(f\), and the peaks of \(f\) show where outcomes are likely. The shape of \(f\) also shows whether the distribution is symmetric, skewed, or heavy-tailed. The CDF is easier to use for calculations, since \(F(x)\) is already the area under \(f\) from \(-\infty\) to \(x\). So \(f\) is large where \(F\) rises steeply and near zero where \(F\) is flat. Just as \(F\) is like the ECDF \(\hat{F}\) with infinite data, you can think of \(f\) as a histogram \(\hat{f}\) with infinite data.
In R, you work with continuous distributions using these functions
dXXXdensity, \(f(x)\) for particular values \(x\)pXXXdistribution, \(F(x)\) for particular values \(x\)rXXXgenerate random variables according to the distribution
where XXX is the distribution name (unif, exp, norm)
Continuous Uniform
The simplest continuous random variable is the one with no preferred region: every value in an interval is equally likely. A Continuous Uniform random variable on the interval \([\theta_{L},\theta_{H}]\) is equally likely to land anywhere in \([\theta_{L},\theta_{H}]\), with density \(f(x) = 1/(\theta_{H}-\theta_{L})\) for \(x~\text{in}~[\theta_{L},\theta_{H}]\) and \(0\) otherwise.
The Continuous Uniform is useful as a reference distribution. Its flat density makes it a natural “no information” baseline. Many of R’s other random-number functions start from uniform draws like those from runif. The full specification gathers sample space, density, and cumulative function in one place: \[\begin{aligned}
X_{i} &~\text{in}~[\theta_{L},\theta_{H}] \\
f(x) &= \begin{cases}
1/(\theta_{H}-\theta_{L}) & x~\text{in}~[\theta_{L},\theta_{H}] \\
0 & \text{Otherwise}
\end{cases} \\
F(x) &= \begin{cases}
0 & x < \theta_{L} \\
(x-\theta_{L})/(\theta_{H}-\theta_{L}) & x~\text{in}~[\theta_{L},\theta_{H}] \\
1 & x > \theta_{H}.
\end{cases}
\end{aligned}\]
Note that the standard uniform uses the unit interval \([0,1]\) and is the special case \(\theta_{L}=0, \theta_{H}=1\). The density is \(f(x)=1\) and CDF \(F(x)=x\).
Code
## MAIN EXAMPLE
runif(3) # 3 draws
## [1] 0.70842381 0.03178858 0.02837421
# Empirical Density
x3_hat <- runif(2000)
hist(x3_hat, breaks=20, border=NA, main=NA, freq=FALSE)
# Theoretical Density
x <- seq(-0.1, 1.1, by=.001)
fx <- dunif(x)
lines(x, fx, col=rgb(0, 0, 1, .8), lty=2)
Code
# CDF example 1
P_low <- punif(0.25)
P_low
## [1] 0.25
# Uncomment to show via PDF
# x_low <- seq(0, 0.25, by=.001)
# fx_low <- dunif(x_low)
# polygon( c(x_low, rev(x_low)), c(fx_low, fx_low*0),
# col=rgb(0, 0, 1, .25), border=NA)
# CDF example 2
P_high <- 1-punif(0.25)
P_high
## [1] 0.75
# Uncomment to show via PDF
# x_high <- seq(0.25, 1, by=.001)
# fx_high <- dunif(x_high)
# polygon( c(x_high, rev(x_high)), c(fx_high, fx_high*0),
# col=rgb(0, 0, 1, .25), border=NA)
# CDF example 3
P_mid <- punif(0.75) - punif(0.25)
P_mid
## [1] 0.5
# Uncomment to show via PDF
# x_mid <- seq(0.25, 0.75, by=.001)
# fx_mid <- dunif(x_mid)
# polygon( c(x_mid, rev(x_mid)), c(fx_mid, fx_mid*0),
# col=rgb(0, 0, 1, .25), border=NA)Exponential
The sample space is any positive number.2 An Exponential random variable has a single rate parameter, \(\lambda>0\). \[\begin{aligned} X_{i} &~\text{in}~[0,\infty) \\ f(x) &= \lambda \exp\left\{ -\lambda x \right\} \\ F(x) &= \begin{cases} 0 & x < 0 \\ 1- \exp\left\{ -\lambda x \right\} & x \geq 0. \end{cases} \end{aligned}\]
Code
## MAIN EXAMPLE
rexp(3) # 3 draws
## [1] 3.437327 1.634091 0.608449
x5_hat <- rexp(2000)
hist(x5_hat, breaks=20,
border=NA, main=NA,
freq=FALSE, ylim=c(0, 1), xlim=c(0, 10))
x <- seq(0, 10, by=.1)
fx <- dexp(x)
lines(x, fx, col=rgb(0, 0, 1, .8), lty=2)
The geometric distribution, a discrete version of the exponential, can also describe real counts (Feller 1968).
Normal (Gaussian)
For continuous data spread symmetrically around a center, the default model is the bell curve. A Normal (or Gaussian) random variable (Gauss 1809) has a bell-shaped density on the real line, with two parameters: the mean \(\mu\) (the center) and the standard deviation \(\sigma\) (the spread). The Normal is useful for measurements that cluster symmetrically around a typical value, such as heights, test scores, and measurement errors. We call it “Normal” because it appears again and again, both as a description of real data and as the limiting shape for sample averages. The full PDF spells out the parameters \(\mu~\text{in}~(-\infty,\infty)\) and \(\sigma > 0\): \[\begin{aligned} X_{i} &~\text{in}~(-\infty,\infty) \\ f(x) &= \frac{1}{\sqrt{2\pi \sigma^2}} \exp\left\{ \frac{-(x-\mu)^2}{2\sigma^2} \right\} \end{aligned}\] The CDF, \(F(x)\), has no closed expression. Despite the complicated formula, the shape is simple: a bell centered at \(\mu\), with most of the probability within a few multiples of \(\sigma\) on either side.
Code
## MAIN EXAMPLE
rnorm(3) # 3 draws
## [1] -1.7749409 0.3200881 -1.1568385
x6_hat <- rnorm(2000)
hist(x6_hat, breaks=20,
border=NA, main=NA,
freq=FALSE, ylim=c(0, .4), xlim=c(-4, 4))
x <- seq(-10, 10, by=.025)
fx <- dnorm(x)
lines(x, fx, col=rgb(0, 0, 1, .8), lty=2)
Even though the distribution function is complex, we can compute CDF values using the computer.
Code
pnorm( c(-1.645, 1.645) ) # 10%
## [1] 0.04998491 0.95001509
pnorm( c(-2.576, 2.576) ) # 1%
## [1] 0.004997532 0.9950024684.3 Exercises
Comment the script you wrote for this chapter, then restart R and check that it runs from a clean session, then check the script with AI as explained in Working with AI. Write three sentences from memory on the main statistical idea of this chapter, and ask the assistant what is wrong, vague, or missing. Finish with your own questions about whatever you found hardest.
A Multinoulli random variable has outcomes \(\{1,2,3,4\}\) with probabilities \(\{0.1, 0.3, 0.4, 0.2\}\). Using the CDF, compute \(\text{Prob}(X_{i} \leq 2)\), \(\text{Prob}(X_{i} > 3)\), and \(\text{Prob}(1 < X_{i} \leq 3)\). Show your work.
Suppose \(X_{i}\) is normally distributed with \(\mu=10\) and \(\sigma=4\). Using
pnorm, compute the probability that \(X_{i}\) falls between \(6\) and \(14\). Then compute the probability that \(X_{i}\) is more than two standard deviations away from the mean, i.e., \(\text{Prob}(X_{i} < 2 \text{ or } X_{i} > 18)\).In R, generate \(2000\) draws from an exponential distribution with \(\lambda=0.5\) using
rexp(2000, rate=0.5). Plot a histogram withfreq=FALSEand overlay the theoretical density usinglinesanddexp. Then usepexpto compute the exact probability that a draw exceeds \(4\).
Further Reading
Many random variables are related to each other. Also note that numbers randomly generated on your computer cannot be truly random, they are “pseudorandom.”
- https://en.wikipedia.org/wiki/Relationships_among_probability_distributions – Overview of how common distributions (Normal, Chi-squared, Exponential, etc.) connect to each other.
- https://www.math.wm.edu/~leemis/chart/UDR/UDR.html – Interactive chart showing transformations and limiting relationships among univariate distributions.
- https://learningstatisticswithr.com/book/probability.html – Introduction to probability distributions with worked R examples.
Recall
This chapter introduced random variables. A random variable \(X_{i}\) describes data we have not seen yet, and a realized value \(\hat{x}_{i}\) is one draw. The discrete families were the Bernoulli, Uniform, and Multinoulli, and the continuous families were the Uniform, Exponential, and Normal. We described each with the CDF \(F(x)=\text{Prob}(X_{i} \leq x)\), each discrete variable also with the PMF \(p(x)\), and each continuous variable also with the PDF \(f(x)\). The four-sided die example used each CDF rule. With \(\text{Prob}(X_{i} \leq 3) = 3/4\), the right-tail probability is \(\text{Prob}(X_{i} > 3) = 1/4\). The in-interval probability is \(\text{Prob}(1 < X_{i} \leq 3) = 3/4 - 1/4 = 2/4\). The out-of-interval probability is \(\text{Prob}(X_{i} \leq 1 \text{ or } X_{i} > 3) = 1/4 + 1/4 = 2/4\).
This is the general formula using CDFs, and you can verify it works in this instance by directly adding the probability of each 2 or 3 event: \(\text{Prob}(X_{i} = 2) + \text{Prob}(X_{i} = 3) = 1/4 + 1/4 = 2/4\).↩︎
In other classes, you may further distinguish types of random variables based on whether their maximum value is theoretically finite or infinite.↩︎






