# Writing a function in R that imitates rbinom [closed]

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)


## closed as off-topic by Stephan Kolassa, Silverfish, COOLSerdash, Andy, GreenparkerJul 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.

• 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

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).