Introduction
Rcpp integrates C++ code into R for performance. It speeds up computationally intensive operations.
Basic Rcpp
library(Rcpp)
# Create C++ function
cppFunction('
int add(int x, int y) {
return x + y;
}
')
add(2, 3)
Using Vectors
cppFunction('
NumericVector squaring(NumericVector x) {
return x * x;
}
')
SourceCpp
// In file: functions.cpp
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double sum_cpp(NumericVector x) {
return sum(x);
}
')
library(Rcpp)
sourceCpp("functions.cpp")
Performance Comparison
library(microbenchmark)
microbenchmark(
R = sum(x),
Cpp = sum_cpp(x)
)
Summary
Rcpp provides C++ speed in R. Use it for performance-critical code.