| name | Rcpp |
| description | R Rcpp package for C++ integration. Use for seamless R and C++ integration. |
Rcpp
Seamless R and C++ integration.
Basic Function
#include <Rcpp.h>
using namespace Rcpp;
double sumC(NumericVector x) {
int n = x.size();
double total = 0;
for (int i = 0; i < n; i++) {
total += x[i];
}
return total;
}
library(Rcpp)
sourceCpp("myfile.cpp")
sumC(1:10)
Inline C++
library(Rcpp)
cppFunction('
double sumC(NumericVector x) {
int n = x.size();
double total = 0;
for (int i = 0; i < n; i++) {
total += x[i];
}
return total;
}
')
sumC(1:10)
Vector Types
NumericVector x;
NumericMatrix m;
IntegerVector x;
IntegerMatrix m;
CharacterVector x;
LogicalVector x;
List L;
DataFrame df;
Vector Operations
NumericVector vecOps(NumericVector x) {
NumericVector y(10);
NumericVector z = clone(x);
double first = x[0];
double last = x[x.size() - 1];
x["a"] = 1.0;
NumericVector result = sqrt(x) + log(x);
return result;
}
Matrix Operations
NumericMatrix matOps(NumericMatrix m) {
int nrow = m.nrow();
int ncol = m.ncol();
double val = m(0, 0);
NumericVector row = m.row(0);
NumericVector col = m.column(0);
return m;
}
Return List
List returnList(NumericVector x) {
return List::create(
Named("mean") = mean(x),
Named("sd") = sd(x),
Named("data") = x
);
}
DataFrame
DataFrame createDF() {
return DataFrame::create(
Named("x") = NumericVector::create(1, 2, 3),
Named("y") = CharacterVector::create("a", "b", "c")
);
}
Sugar Functions
NumericVector y = abs(x);
NumericVector y = sqrt(x);
NumericVector y = exp(x);
NumericVector y = log(x);
double s = sum(x);
double m = mean(x);
double v = var(x);
double sd = sd(x);
double mn = min(x);
double mx = max(x);
Attributes
NumericVector withAttrs(NumericVector x) {
x.attr("dim") = IntegerVector::create(2, 5);
x.attr("class") = "myclass";
return x;
}