I am learning R and have just started simulating from different probability distributions. I was trying to generate a random variate from the Geometric Distribution. I am not willing to use the inbuilt function rgeom in R for doing the same. Among other methods, I decided to use the result that:
The Geometric distribution is the probability distribution of the number of Bernoulli trials needed to get one success.
I wrote the function for generating one Bernoulli variable as in my previous post named as ber, with p being the success probability.
Now to generate a Geometric variable, I can run a loop (I used a repeat loop here) and continuously generate a Bernoulli variable, check if it is a success or not and so on...
I did it like the following:
geom<-function(p)
{
x<-1
repeat
{
if(ber(p)==1) break
x<-x+1
}
return(x)
}
One output as generated by R is:
geom(0.035)
[1] 9
What I want to do and where am I stuck:
I want to use a vectorized approach instead of this repeat loop method to generate a Geometric variable but I seem to have run out of ideas as to how that can be achieved. Any helps/suggestions and hints are very much welcome in here.
Note 1: As to why I defined a new function geom(p), I originally planned to generate not one, but many (say n) Geometric variates. I figured that defining a function as like this, and then using the replicate function to generate more similar variables with the same success probability is easier.
Note 2: I really apologize if some of my previous posts seem similar (in the sense that asking for suggestion for replacing a loop with some vector methods), but I am a newbie in R and I am still learning about vectorized methods.