0
$\begingroup$

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)
$\endgroup$

closed as off-topic by Stephan Kolassa, Silverfish, COOLSerdash, Andy, Greenparker Jul 14 '16 at 12:18

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question appears to be off-topic because EITHER it is not about statistics, machine learning, data analysis, data mining, or data visualization, OR it focuses on programming, debugging, or performing routine operations within a statistical computing platform. If the latter, you could try the support links we maintain." – Stephan Kolassa, Silverfish, COOLSerdash, Andy, Greenparker
If this question can be reworded to fit the rules in the help center, please edit the question.

  • $\begingroup$ 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 $\endgroup$ – Silverfish Jul 14 '16 at 10:34
1
$\begingroup$

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.

$\endgroup$

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