# Simulate a mixture distribution in R

Hi just wanna try to simulate a mixture distribution with combination of a normal distribution and a non-central t distribution,

the random variable Z is defined as:

$$Z = nX+(1-n)Y$$

where

$$n \sim \mathrm{Bernoulli}(\pi)$$

$$X \sim \mathrm{Normal}(\mu_1, \sigma_1)$$

$$Y \sim t_\nu(\mu_2, 1)$$

i have the codes as below but a bit inefficient, anyone can help to improve?

    mix.dist.alt <- function(n,mix.par,mu1,sigma1,mu2,df) {
#Purpose: Alternative implementation of routine to sample n values
#  from the mixture distribution
#Inputs:
# n - number of samples to return
# mix.par - pi in the practical notes -- proportion of samples from norm dist
# mu1 - mean of norm dist
# sigma1 - sd of norm dist
# mu2 - mean of t dist
# df - df for t dist
#Outputs:
# vector of n values from the mixture distribution
#create results vector
Z<-numeric(n)
#go through each observation...
for(i in 1:n){
#...determine if it comes from the normal or t distribution
if(rbinom(1,1,mix.par)==1) {
#normal distribution
Z[i]<-rnorm(1,mu1,sigma1)
} else {
#t distribution
Z[i]<-mu2+rt(1,df)
}
}
return(Z)
}


Much simpler solution is to simply take $k$ values from one distribution and $N-k$ values from the other, where $k$ follows binomial distribution ($N$ Bernoulli trials):
mix.dist.alt2 <- function(n, mix.par, mu1, sigma1, mu2, df) {

• Thank you so much for your codes, but when i interpret the numbers for the function still an error exists. codes as follow: n<-10000 mix.par<-3.14 mu1<-0 sigma1<-0 mu2<-1 df<-1 and it returns like: mix.dist(n,mix.par,mu1,sigma1,mu2,df) Show Traceback Rerun with Debug Error in rnorm(k, mu1, sigma1) : invalid arguments In addition:  Warning message: In rbinom(1, n, mix.par) : NAs produced – ChokinCaby Nov 3 '15 at 17:42
• @ChokinCaby mix.par is probability, so has to fit the $[0, 1]$ range. – Tim Nov 3 '15 at 17:46
• @ChokinCaby In this case mix.par is $p$ parameter for Bernoulli or Binomial distribution. If you find the answer helpful you can accept it (the "v" button). – Tim Nov 3 '15 at 18:04