Chapter 3 Basic usage

You can use your Rcpp function in 3 steps.

  1. Writing Rcpp source code
  2. Compiling the code
  3. Executing the function

3.1 Writing your Rcpp code

The below code defines a function rcpp_sum() that calculates the sum of a vector. Save this content as a file named “sum.cpp”.

sum.cpp

//sum.cpp
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double rcpp_sum(NumericVector v){
    double sum = 0;
    for(int i=0; i<v.length(); ++i){
        sum += v[i];
    }
    return(sum);
}

3.1.1 Format for defining a function in Rcpp.

The following code shows the basic format for defining a Rcpp function.

#include<Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
RETURN_TYPE FUNCTION_NAME(ARGUMENT_TYPE ARGUMENT){

    //do something

    return RETURN_VALUE;
}
  • #include<Rcpp.h> : This sentence enables you to use classes and functions defined by the Rcpp package.

  • // [[Rcpp::export]]:The function defined just below this sentence will be accessible from R. You need to attach this sentence to every function you want to use from R.

  • using namespace Rcpp; : This sentence is optional. But if you did not write this sentence, you have to add the prefix Rcpp:: to specify classes and functions defined by Rcpp. (For example, Rcpp::NumericVector)

  • RETURN_TYPE FUNCTION_NAME(ARGUMENT_TYPE ARGUMENT){}:You need to specify data types of functions and arguments.

  • return RETURN_VALUE;return statement is mandatory if your function would return a value. However, if your function do not return a value (i.e. RETURN_TYPE is void), the return statement can be omitted.

3.2 Compiling the code

The function Rcpp::sourceCpp() will compile your source code and load the defined function into R.

library(Rcpp)
sourceCpp('sum.cpp')

3.3 Executing the function

You can use your Rcpp functions as usual R functions.

> rcpp_sum(1:10)
[1] 55

> sum(1:10)
[1] 55