I am new to recursion in R. I am trying to generate exponential random variables that meet a certain condition in R. Here is a simple example showing my attempt to generate two independent exponential random variables.
CODE
#### Function to generate two independent exponential random variable that meet two criteria
gen.exp<-function(q1,q2){
a=rexp(1,q1) # generate exponential random variable
b=rexp(1,q2) # generate exponential random variable
if((a>10 & a<10.2) & (a+b>15)){ # criteria the random variables must meet
return(c(a,b))
}else{
return(gen.exp(q1,q2)) #if above criteria is not met, repeat the process again
}
}
EXAMPLE: q1=.25, q2=2
gen.exp(.25,2)
When I run the above code, I get the following errors:
- Error: evaluation nested too deeply: infinite recursion / options(expressions=)?
- Error during wrapup: evaluation nested too deeply: infinite recursion / options(expressions=)?
I have already tried modifying options(expressions=10000)
and in order to allow R to increase the number of iterations. That has does not seem to help with my case (maybe I am not using the option correctly). I understand generating continuous distributions with stringent criteria as above maybe the problem. Having said that, is there anyway to avoid the errors? Or at least repeat the recursion whenever an error occurs? Is recursion an over kill here? Are there simpler/better ways of generating the desired random variables?
I appreciate any insights.
You are using a simple rejection sampler with two conditions
a > 10 & a < 10.2
a+ b > 15
However, the chance of matching both of them is low, i.e. very slow. However, since you are interested in exponential random numbers, we can avoid simulating numbers we would reject.
To generate an exponential random number, we use the formula
where
U
is aU(0,1)
random number. So to generate values from the exponential distribution larger than 10 (say), we just door in R code
We can use a similar trick for upper bounds.
Using @Roland's function from above, this gives
Notice, I've also printed out how many iterations it took. For your parameters, I need around 2 iterations.