lundi 18 mars 2019

Simulate a numeric variable given probabilities by intervals in R without if else

I was trying to think about an elegant/easier way without using if() else().

For example, I have the distribution of a population's age by intervals, let's say :

 Age     Prob
 40-44   20 %
 44-49   15 %
 50-54   8 %
 55-59   12 %

How to simulate such data ?

I was also thinking about sample() to write something like this :

sample(c(40:59), size = 100, replace = TRUE, prob = c(0.2, 0.2, 0.2, 0.2, 0.2, 0.15, 0.15 ...))

I guess it can work but it's not very efficient if more complex data such as :

 Age    Prob (F) Prob(M)
 40-44   15 %     5 %
 44-49   5 %      10 %
 50-54   4 %      4 %
 55-59   3 %      9 %

Is it possible to do this ?




Aucun commentaire:

Enregistrer un commentaire