Get startedGet started for free

Scalar random number generation

When you write R code, it usually makes sense to generate random numbers in a vectorized fashion. When you are in C++ however, you are allowed (even by your guilty conscience) to use loops and process the data element by element.

The R API gives you functions to generate a random number from one of the usual distributions, and Rcpp makes these functions accessible in the R:: namespace. For example, R::rnorm(2, 3) gives you one random number from the Normal distribution with mean 2 and standard deviation 3. Notice that the n argument from the "real" rnorm() is not present. The Rcpp version always returns one number.

Go ahead and complete the function definition of positive_rnorm().

Note: This last chapter is hard, so don't get discouraged if you can't complete the exercises in the first attempt. Remember the reward for completing this course: dramatically improving the performance of your R code!

This exercise is part of the course

Optimizing R Code with Rcpp

View Course

Exercise instructions

  • Specify the return value, out as a numeric vector of size n.
  • Read the looping code to see what each does.
  • Generate a normal random number of mean mean and standard deviation sd, assigning to out[i].
  • While out[i] is less than or equal to zero, try again.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

#include 
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector positive_rnorm(int n, double mean, double sd) {
  // Specify out as a numeric vector of size n
  ___ ___(___);
  
  // This loops over the elements of out
  for(int i = 0; i < n; i++) {
    // This loop keeps trying to generate a value
    do {
      // Call R's rnorm()
      out[i] = ___;
      // While the number is negative, keep trying
    } while(___);
  }
  return out;
}

/*** R
  positive_rnorm(10, 2, 2)
*/
Edit and Run Code