Overview

The exercises below have been written assuming that you have never programmed in C/C++ before. If you have previous experience, feel free to alter the questions to suit your background.

Exercise 1

  1. Load the Rcpp package r library("Rcpp") and run the following code ```r cppFunction(" double add_c(double x, double y) { double value = x + y; return value; } ")
1. Call the function `add_c` and make sure it works. What happens if you pass it a vector
or a character to the function?
1. Hard: Change the function to calculate $x^y$. Hint: Google taking powers in C++.

```r
 cppFunction('
      double pow_c(double x, double y){
        double value = pow(x, y);
        return value;
      }
    ')

Exercise 2

  1. Create a directory called src - this is a standard directory name for computer code. It's short for source. This is where you should keep your C++ code.
  2. Create a file called add.cpp and move the add_c function (with necessary headers) to the file.
    • Compile the file and call the add_c function.
  3. Similar to above, but add a function called subtract_c.

Exercise 3

  1. Write an R function that calculates the sample standard deviation - you are not allowed to use sum, mean, sd or var, i.e. Use a for loop. The formula for the standard deviation is

$$ \sigma = \sum_{i=0}^n (x_i - \mu) $$ where $\mu$ is the mean. Hint you will need a function to calculate the mean, i.e. mean_r

mean_r = function(x) {
  n = length(x)
  m = 0
  for (i in seq_along(x)) 
    m = m + x[i] / n
  m
}

sd_r = function(x) {
  n = length(x)
  var = 0; m = mean_r(x)
  for (i in seq_along(x)) {
    var = var + (x[i] - m)^2
  }
  sqrt(var / (n - 1))
}
x = rnorm(10)
mean_r(x); mean(x)
sd_r(x); sd(x)
  1. Write a C function that calculates the standard deviation.
## Should be in a file
double mean_c(NumericVector x){
  int i;
  int n = x.size();
  double mean = 0;

  for(i=0; i<n; i++) {
    mean = mean + x[i]/n;
  }
  return mean;
}
double sd_c(NumericVector x){
  int i;
  int n = x.size();
  double mean = mean_c(x);
  double var=0;
  for(i=0; i<n; i++) {
    var = var + pow(x[i] - mean, 2);
  }
  return pow(var/(n-1), 0.5);
}
  1. Using microbenchmark, compare your C version to your R function.
    • Use the base R function sd as a baseline.

Hint: There's a chapter on RCpp Efficient R programming



jr-packages/jrBig documentation built on Jan. 1, 2020, 2:02 p.m.