25.3 Data frames, functions, and attributes

Lists and Dataframes

Contrived example to illustrate how to access a dataframe from c++:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double mpe(List mod) {
  if (!mod.inherits("lm")) stop("Input must be a linear model");

  NumericVector resid = as<NumericVector>(mod["residuals"]);
  NumericVector fitted = as<NumericVector>(mod["fitted.values"]);

  int n = resid.size();
  double err = 0;
  for(int i = 0; i < n; ++i) {
    err += resid[i] / (fitted[i] + resid[i]);
  }
  return err / n;
}
mod <- lm(mpg ~ wt, data = mtcars)
mpe(mod)
#> [1] -0.01541615
  • Note that you must cast the values to the required type. C++ needs to know the types in advance.

Functions

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
RObject callWithOne(Function f) {
  return f(1);
}
callWithOne(function(x) x + 1)
#> [1] 2
  • Other values can be accessed from c++ including

    • attributes (use: .attr(). Also .names() is alias for name attribute.
    • Environment, DottedPair, Language, Symbol , etc.