1. Learn
  2. /
  3. Courses
  4. /
  5. Optimizing R Code with Rcpp

Connected

Exercise

Sampling from a mixture of distributions (II)

The complete algorithm for sampling from a mixture distribution is:

  1. Choose a component.
  2. Generate a normal random number using the mean and standard deviation of the selected component.

choose_component(), from the last exercise, is provided. Here you'll complete the second step and complete the definition of rmix().

Instructions

100 XP
  • Check that there are as many standard deviations as weights. That is, the size of sds is the same as d.
  • Calculate total_weight as the sum of the weights.
  • Choose a component by calling choose_component().
  • Simulate from the chosen component by generating a normal random number with the jth element of means and sds.