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.