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.
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;
}
')
src - this is a standard directory name for computer code.
It's short for source. This is where you should keep your C++ code.add.cpp and move the add_c function (with necessary headers)
to the file.add_c function.subtract_c.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)
## 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); }
microbenchmark, compare your C version to your R function.sd as a baseline.Hint: There's a chapter on RCpp Efficient R programming
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.