1
$\begingroup$

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

$\endgroup$
  • 1
    $\begingroup$ 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). $\endgroup$ – Kyle Nov 12 '17 at 14:55
  • $\begingroup$ @kyle, can you please provide me a bit more explanation about this approach? May be a link or code will be more useful. $\endgroup$ – kishore Nov 13 '17 at 10:00
  • $\begingroup$ @kishore: the mixture approach is the one I described in my answer [which I wrote in exact synchronicity with Kyle!] $\endgroup$ – Xi'an Nov 13 '17 at 10:24
1
$\begingroup$

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).

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.