Rcppを使う練習:RcppでRとC++のやりとり

  • RcppはRでC++を使うための橋渡し援助のパッケージ
  • そのRcppが、データや値をRの世界とC++の世界とでやりとりすすために持っている関数を使う例を示したパッケージがRcppExamples(こちら)
  • ついでにRcppのクイック・レファレンス(こちら)
  • 例をみよう
 void convolve(double *a, int *na, double *b, int *nb, double *ab)
     {
         R_len_t i, j, nab = *na + *nb - 1;
     
         for(i = 0; i < nab; i++)
             ab[i] = 0.0;
         for(i = 0; i < *na; i++)
             for(j = 0; j < *nb; j++)
                 ab[i + j] += a[i] * b[j];
     }
      • これをRから呼ぶとき
     conv <- function(a, b)
         .C("convolve",
            as.double(a),
            as.integer(length(a)),
            as.double(b),
            as.integer(length(b)),
            ab = double(length(a) + length(b) - 1))
#include <Rcpp.h>
RcppExport SEXP convolve3cpp(SEXP a, SEXP b) {
Rcpp::NumericVector xa(a);
Rcpp::NumericVector xb(b);
int n_xa = xa.size(), n_xb = xb.size();
int nab = n_xa + n_xb - 1;
Rcpp::NumericVector xab(nab);
for (int i = 0; i < n_xa; i++)
for (int j = 0; j < n_xb; j++)
xab[i + j] += xa[i] * xb[j];
return xab;
}