# Generate random number from a specific probability mass in R

How can I generate sample from a distribution with probability mass $P(X=x)$ in R? I know that probability mass, but it is not from a known distribution, also it is not linear, instead it has a complicated form. Can I use the inverse cdf method on the density, by working out the cdf and inverting it $X=F^{-1}(U)$?

• Use the sample function. With the argument replace=TRUE this simulates from the specified pmf using the alias method, see related thread Apr 14, 2017 at 20:15
• @JarleTufto Can that approach be used if there are infinitely many $x$ with $P(X=x)>0$? Apr 14, 2017 at 20:19
• @JarleTufto This assumes that $X$ has finite support.
– nth
Apr 14, 2017 at 20:20
• The OPs suggested approach won't work because for discrete distributions the transformation is not 1-1. Apr 14, 2017 at 20:21
• The thread that Jarie Tufto linked indicates that the method is efficient when X has finite support. It works when there are infinite values as would be he case for the Poisson distribution but efficiency is not claimed in that case. Apr 14, 2017 at 20:27

Yes, you can use the inverse CDF method. Let $x_1, x_2, \dots$ be the (possibly infinite) sequence of elements which have positive probability masses $p_1,p_2,\dots>0$. Let $I\in \mathbb{N}$ have distribution $\mathbb{P}(I=i)=p_i.$ Generate a uniform random variable $U$ and then let $J$ be such that $$\mathbb{P}(I<J)=F_I(J) \le U < F_I(J+1).$$ Take $X=x_J$. Then $$\mathbb{P}(X=x_j)=\mathbb{P}(F_I(j)\le U < F_I(j+1))=F_I(j+1)-F_I(j)=p_j.$$