Skip to content

Instantly share code, notes, and snippets.

@pati-ni
Created March 13, 2018 11:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pati-ni/9f2cf2f8c5467784145b26262cfd588c to your computer and use it in GitHub Desktop.
Save pati-ni/9f2cf2f8c5467784145b26262cfd588c to your computer and use it in GitHub Desktop.
R internals matrix manipulations
#include <RcppArmadillo.h>
#include <Rinternals.h>
#include <Rcpp.h>
#include <iostream>
SEXP createMat(const SEXP& input)
{
arma::mat matrix(REAL(input), Rf_nrows(input), Rf_ncols(input), false);
// Create new SEXP
unsigned int ncols = Rf_ncols(input);
unsigned int nrows = Rf_nrows(input);
SEXP res = Rf_allocMatrix(REALSXP, ncols, nrows);
// Protect it from garbage collector
res = Rf_protect(res);
// Pass it to armadillo
arma::mat result(REAL(res), Rf_nrows(res), Rf_ncols(res), false);
// Do some processing
//...
// return the new array
return res;
}
#include <RcppArmadillo.h>
#include <Rinternals.h>
#include <Rcpp.h>
#include <iostream>
SEXP readFromMat(const SEXP& mat)
{
// Cast it as a double vector
double* p = REAL(mat);
//This outputs Rf_nrows(mat) * Rf_ncols(mat)
std::cout << <<LENGTH(mat) << std::endl;
// pass matrix to armadillo to process the array
arma::mat matrix(p, Rf_nrows(mat), Rf_ncols(mat), false);
// do some processing
// ...
return mat;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment