vendredi 19 avril 2019

Simulation of multiple binomial random numbers in R

I have the following algorithm

Step 1. Generate X1=x1~Bin(6,1/3)

Step 2. Generate X2|X1=x1~Bin(6-x1,(1/3)/(1-1/3))

Step 3. Generate X3|X1=x1,X2=x2~Bin(6-x1-x2,(1/3)/(1-1/3-1/3))

Step 4. Repeat step 1-3 N times.

I think in r is as follows

mult_binom<-function(n) #n=6
{
  n=1000
  random_vectors<-Matrix(0,n,3)

  for(i in 1:n){

    X1<-rbinom(n,3,1/3) 

    X2<-rbinom(n-X1,3,(1/3)/(1-(1/3)))

    X3<-rbinom(n-X1-X2,3,(1/3)/(1-(1/3)-(1-3)))


    arr<-c(X1,X2,X3)


  }
  for(j in 1:n){

    random_vectors[j]<-arr[j]
  }
  return(random_vectors)
}

Calling the function as mult_bin(6) yields

enter image description here

and continues up to [1000,]

Why?

I was not expecting such matrix, why are dots there?

Also why only 1 2 and 3 numbers appear?

What am I doing wrong in the code?




Aucun commentaire:

Enregistrer un commentaire