Search code examples
runiformmixture

Mixture of 2 uniform random variables


I need help creating a mixture that is 1/3 Unif (0,7) and 2/3 Unif(9,10) I used

library(distr)

X <- UnivarMixingDistribution(Unif(0,7),Unif(9,10),mixCoeff = c((1/3),(2/3)))

But I'm not sure if it is good because when plotting X, it returns a scatterpoint that does not really make any sense .

Thanks in advance for your help !


Solution

  • I don't know the function distr::UnivarMixingDistribution but this is easy to implement from scratch:

    1. We fix the seed for reproducibility

      # Set fixed seed
      set.seed(2017);
      
    2. Specify the number of sampling points

      # Sample N points
      N <- 1000;
      
    3. Specify the mixing factors and limits of both uniform distributions

      # Weights and limits of both uniform distibutions
      weights <- c(1/3, 2/3);
      range <- list(list(min = 0, max = 7), list(min = 9, max = 10));
      
    4. We now sample N points

      # Sample
      x <- unlist(mapply(function(x, y) runif(x * N, y$min, y$max), weights, range))
      
    5. Let's plot the distribution of x

      ggplot(data.frame(x = x), aes(x)) + geom_histogram(bins = 100)
      

    enter image description here