In: Statistics and Probability
How can I make my own function for rbinom(n, size, prob) in R.
So, basically I want to build my own rbinom function that gives me the same result as rbinom that's built in R software.
The function is below
R code with comments (all statements starting with # are comments)
#define the rbinom function
myRbinom<-function(n,size,prob){
#draw n*size numbers from uniform random (0,1)
u<-runif(n*size)
#arrange this into a matrix of size (n x size): n rows
and size columns
u<-matrix(u,nrow=n,ncol=size)
#set the values which are less than prob as
success
success<-u<prob
#count the number of successes for each row
x<-apply(success,1,sum)
return(x)
}
## now let us try this out for number of trials = 10 and success probability =0.2.
We know that the theoretical mean for a Binomial distribution (or the expectation) is trials*prob = 10*0.2=2
the theoretical variance is trials*prob*(1-prob) = 10*0.2*0.8=1.6
Let us see if we can get these values
R code
#set the random seed
set.seed(123)
n<-10000
size<-10
p<-0.2
y<-myRbinom(n,size,p)
#Check if this looks good
sprintf('Estimated mean of y is %.4f',mean(y))
sprintf('Estimated variance of y is %.4f',var(y))
sprintf('The theoretical mean of Y (E[Y]) is %.4f',size*p)
sprintf('The theoretical variance of Y is %.4f',size*p*(1-p))
## get this output
the estimated mean and variances are close to the theoretical values. Hence the function looks good.