I am trying to make a function in order to generate n
random numbers from negative binomial distribution.
To generate it, I first made a function to generate n
random variables from geometric distribution. My function for generating n
random numbers from geometric distribution as follows:
rGE<-function(n,p){
I<-rep(NA,n)
for (j in 1:n){
x<-rBer(1,p)
i<-1 # number of trials
while(x==0){
x<-rBer(1,p)
i<-i+1
}
I[j]<- i
}
return(I)
}
I tested this function (rGE
), for example for rGE(10,0.5)
, which is generating 10
random numbers from a geometric distribution with probability of success 0.5, a random result was:
[1] 2 4 2 1 1 3 4 2 3 3
In rGE
function I used a function named rBer
which is:
rBer<-function(n,p){
sample(0:1,n,replace = TRUE,prob=c(1-p,p))
}
Now, I want to improve my above function (rGE
) in order to make a function for generating n
random numbers from a negative binomial function. I made the following function:
rNB<-function(n,r,p){
I<-seq(n)
for (j in 1:n){
x<-0
x<-rBer(1,p)
i<-1 # number of trials
while(x==0 & I[j]!=r){
x<-rBer(1,p)
i<-i+1
}
I[j]<- i
}
return(I)
}
I tested it for rNB(3,2,0.1)
, which generates 3 random numbers from a negative binomial distribution with parametrs r=2
and p=0.1
for several times:
> rNB(3,2,0.1)
[1] 2 1 7
> rNB(3,2,0.1)
[1] 3 1 4
> rNB(3,2,0.1)
[1] 3 1 2
> rNB(3,2,0.1)
[1] 3 1 3
> rNB(3,2,0.1)
[1] 46 1 13
As you can see, I think my function (rNB
) does not work correctly, because the results always generat 1
for the second random number.
Could anyone help me to correct my function (rNB
) in order to generate n
random numbers from a negative binomial distribution with parametrs n
, r
, and p
. Where r
is the number of successes and p
is the probability of success?
[[Hint: Explanations regarding geometric distribution and negative binomial distribution: Geometric distribution: In probability theory and statistics, the geometric distribution is either of two discrete probability distributions:
- The probability distribution of the number X of Bernoulli trials needed to get one success, supported on the set { 1, 2, 3, ... }.
- The probability distribution of the number Y = X − 1 of failures before the first success, supported on the set { 0, 1, 2, 3, ... }
Negative binomial distribution:A negative binomial experiment is a statistical experiment that has the following properties: The experiment consists of x repeated trials. Each trial can result in just two possible outcomes. We call one of these outcomes a success and the other, a failure. The probability of success, denoted by P, is the same on every trial. The trials are independent; that is, the outcome on one trial does not affect the outcome on other trials. The experiment continues until r successes are observed, where r is specified in advance. ]]
rnbinom
? And where isrBer
defined? Is it justrBer <- function(n, p) rbinom(n, 1, p)
? – Allan Cameronsample
though. Is this the only random - generating function you want to use? – Allan Cameron