0

I'm just learning to write functions in R for the first time and I'm trying to mimic the rbinom() function in R. I've written some code but I'm not sure if it is repeating what rbinom() does. Also how do I return multiple observations in one go, like rbinom(). Thirdly, is there a more efficient way to create a function like this? I've used the example of n=100, p=0.1 so far

    myrbinom<-function(x){
    x<-runif(n) 
    count=0
      for(i in 1:n){
        if(x[i]<=p){
        count=count+1 
        }
       }
    return(count)
    }
    p=0.1
    n=100
    myrbinom(x)
Tim
  • 108,699
  • 20
  • 212
  • 390
  • I think there may be an underling statistical question here - thinking about the algorithm by which `rbinom` may be calculated - but the specific programming aspect isn't really on-topic – Silverfish Jul 14 '16 at 10:34

1 Answers1

1

The function that you wrote certainly does not work the same as rbinom function implemented in R (as you can see in the C source code for it). rbinom uses much more sophisticated algorithm described by Kachitvichyanukul and Schmeiser (1988), but you can also find examples in book by Luc Devoye (1988) that is available online. In general, using direct simulation, as in your code, is rather inefficient way for random generation and in most cases there are better algorithms for it (e.g. inverse transform sampling being one of the most easy to implement).


Kachitvichyanukul, V., & Schmeiser, B. W. (1988). Binomial random variate generation. Communications of the ACM, 31(2), 216-222.

Devroye, L. (1986). Non-Uniform Random Variate Generation. New York: Springer-Verlag.

Tim
  • 108,699
  • 20
  • 212
  • 390