Think of the green lines in the uniform PMF as “sticks” with “labels.”
The “labels” are the different realization, e.g. 1, 2, 3, …, 6.
Place the six sticks in the interval \([0, 1]\) so that they do not overlap.
Sample a uniform real number in \([0, 1]\)
in R: runif(1)
The uniform falls in exactly one of the sticks.
Return the label of that stick.
Mathematical explanation
The above “stick-based” algorithm can be implemented using the cumulative distribution function and a generalization of its inverse known as the quantile function.
Cumulative distribution function (CDF):\(F(x) = \mathbb{P}(X \le x).\)
Quantile function:\(Q(u) = \inf\{x \in \mathbb{R}: u \le F(x)\}\).
Then the “stick-based” algorithm can be written as:
Here dbinom is the R function for the PMF of a binomial (R uses the prefix d___ for densities and PMFs).
We use the fact that many functions in R such as this one are vectorized, i.e. the normal PMF function takes a single point \(x\) and output \(p(x)\) where \(p\) is the PMF; the vectorized version takes vector \((x_1, x_2, \dots)\) and returns \((p(x_1), p(x_2), \dots)\).
The argument type = 'h' instructs the plot function to make the plot “histogram”-like.