Simulate a mixture of two Gaussian distributions
Mixture models can be very difficult to understand, so let's start by simulating a simple mixture model, and then we will advance from there. In this exercise, you will create a Gaussian Mixture Model with two components.
This exercise is part of the course
Mixture Models in R
Exercise instructions
- Simulate 500 samples from a binary variable using
sample()
with a probability of 0.8 for the value 1 and save the results into the objectcoin
. - Then, create a vector
mixture
which samples from two different Gaussian distributions depending on the values ofcoin
in the following way:- When the values of
coin
are 1, sample from a normal distribution with a mean of 5 and sd of 2. - Otherwise, sample from a standard normal distribution.
- When the values of
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create coin object
coin <- ___(c(0,___), size = ___,
replace = TRUE, prob = c(0.2, ___))
# Sample from two different Gaussian distributions
___ <- ifelse(___ == 1, rnorm(n = ___, mean = ___, sd = ___),
rnorm(n = ___))
# Check the first elements
head(mixture)