# Simulating random variables from a discrete distribution II [duplicate]

I have the following discrete probability distribution where $$p$$, $$q$$ and $$r$$ are known constants:

$$P(X=0)=q$$, $$0

$$P(X=1)=1-p-q-r$$, $$0

$$P(X=2)=p$$, $$0

$$P(X=3)=r$$, $$0

How can I sample from this distribution?

To generate $$n$$ independent values from this distribution, you can use:

sample(0:3, size = n, replace = TRUE, prob = c(p, 1-p-q-r, q, r))


For example, here we generate $$n=10^6$$ values and show the sample proportions:

#Generate a large number of values from this distribution
set.seed(1)
p <- 0.11
q <- 0.20
r <- 0.35
n <- 10^6
X <- sample(0:3, size = n, replace = TRUE, prob = c(p, 1-p-q-r, q, r))

#Show sample proportions
table(X)/n

X
0        1        2        3
0.109570 0.340265 0.200222 0.349943

• How do you do this in SPSS? You may be able to create an SPSS syntax file with the sps extension. May 7, 2020 at 14:49

There is a quite simple strategy for discrete distributions such as this with small number of elements in the support:

u <- generate a uniform RV in [0,1]
if u < q: x <- 0
elseif u < 1-p-r: x <- 1
elseif u < 1-r: x <- 2
else x <- 3


This is basically an over simplification of Inverse Transform Sampling.

• How do you do this in SPSS? You may be able to create an SPSS syntax file with the sps extension. May 7, 2020 at 14:49
• I don't know SPSS. But, it's so simple that you should be able to implement it in almost every language you're familiar with. May 7, 2020 at 14:51
• Which programming language did you use? May 7, 2020 at 15:34
• Now I understood. With p = 0.05, q = 0.03 and r = 0.01 in SPSS the syntax is: COMPUTE U=RV.UNIFORM(0,1). RECODE U (0.0 thru 0.03=0) (0.03 thru 0.94=1) (0.94 thru 0.99=2) (ELSE=3). EXECUTE. May 8, 2020 at 8:56
• @ gunes Thanks a lot for all your help. May 8, 2020 at 14:48