Created
March 13, 2018 11:29
-
-
Save pati-ni/9f2cf2f8c5467784145b26262cfd588c to your computer and use it in GitHub Desktop.
R internals matrix manipulations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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