# Generating random number falling in a range with given probabilities

I need to simulate 1000+ values of a variable whose outcome will be in a distinct range with a given probability. Something on the following lines:

Range      Probability
3 - 10      0.2
40 - 80     0.4
120 - 170   0.2
200 - 225   0.15
260 - 300   0.05


Purpose of this is to see the variability of the outcome in a given range. How can I achieve the random numbers following the above pattern? Supporting R code or pointer will be a big help for me.

Thanks

• How about a mixture? Select a range with the probabilities given (this is a discrete random variable). Then randomly generate a value in the chosen range. The later step can be done using any appropriate method (e.g. uniform in the range). – Kyle Nov 12 '17 at 14:55
• @kyle, can you please provide me a bit more explanation about this approach? May be a link or code will be more useful. – kishore Nov 13 '17 at 10:00
• @kishore: the mixture approach is the one I described in my answer [which I wrote in exact synchronicity with Kyle!] – Xi'an Nov 13 '17 at 10:24

There is an infinite number of solutions, since any combination of random generators on each of the intervals with the proper probability meets the constraint: for instance

i=sample(1:5,1,prob=c(.2,.4,.2,.15,.05))
x=runif(1,3,10)*(i==1)+
runif(1,40,80)*(i==2)+
runif(1,120,170)*(i==3)+
runif(1,200,225)*(i==4)++
runif(1,260,300)*(i==5)


is a way to generate such numbers. Which can be improved into

i=sample(1:5,n,rep=TRUE,prob=c(.2,.4,.2,.15,.05))
lob=c(3,40,120,200,260)
upb=c(10,80,170,225,300)
x=runif(n,min=lob[i],max=upb[i],rep=TRUE)


In the event you need to generate integers rather than real numbers (the question does not specify this point), all you need to do is replacing runif(n,min=lob[i],max=upb[i]) with for (t in 1:n) x[t]=sample(lob[i[t]]:upb[i[t]],1) (or some alternative that is more compact).