Search code examples
rprobabilitystat

I have the probability distribution of a random variable, how do I generate a random set of 10 numbers based on this distribution?


There is an answer in python: Generate random variables from a probability distribution

It seems like they are using some built-in distribution function (i.e. exp). I have looked at the random generator functions in R like runif but it seems like I would need to create the function with this probability distribution myself as the prob distribtion that I have is not standard.

e.g. distribution:

distribution = data.table(x = c(1,2,3,4,5,6,7,8,9,10), p = c(0.1,0.1,0.2,0.05,0.05,0.1,0.1,0.2,0.05,0.05))
> distribution
     x    p
 1:  1 0.10
 2:  2 0.10
 3:  3 0.20
 4:  4 0.05
 5:  5 0.05
 6:  6 0.10
 7:  7 0.10
 8:  8 0.20
 9:  9 0.05
10: 10 0.05

Solution

  • I would do it like that:

    sample(distribution$x, size = n, replace = TRUE, prob = distribution$p)
    

    where size = n defines the number of elements you want to sample.