0
$\begingroup$

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)
           }
$\endgroup$
2
$\begingroup$

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) {
  k <- rbinom(1, n, mix.par)
  sample(c(rnorm(k, mu1, sigma1), mu2+rt(n-k, df))) #shuffle the values
}
| cite | improve this answer | |
$\endgroup$
  • $\begingroup$ 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 $\endgroup$ – ChokinCaby Nov 3 '15 at 17:42
  • $\begingroup$ @ChokinCaby mix.par is probability, so has to fit the $[0, 1]$ range. $\endgroup$ – Tim Nov 3 '15 at 17:46
  • $\begingroup$ yes many thx for the help! I just realized that the range restriction. $\endgroup$ – ChokinCaby Nov 3 '15 at 17:59
  • $\begingroup$ @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). $\endgroup$ – Tim Nov 3 '15 at 18:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.