Rcpp: returning array C as a numeric matrix to R
#include <Rcpp.h>
#include <vector>
extern "C"
{
#include "cheader.h"
}
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector cppfunction(NumericVector inputR){
double const* input = inputR.begin();
size_t N = inputR.size();
double output[10*N];
cfunction(input, N, output);
std::vector<double> outputR(output, output + sizeof(output) / sizeof(double));
return wrap(outputR);
}
This works, except I need to manually convert the vector output R to a matrix in R. I could of course also make outputR to a NumericMatrix (or can I?) And then return that, but my real question is that this procedure is optimal? Do I need to convert the output to std :: vector first and then to a numeric vector / matrix, or can I somehow avoid this? I tried to output the output directly, but it didn't work.
source to share
Put this in a file cppfunction.cpp
and run it through library(Rcpp); sourceCpp("cppfunction.cpp")
. Since cfunction
it was not provided, we provide one that adds 1 to each input element:
#include <Rcpp.h>
using namespace Rcpp;
void cfunction(double* x, int n, double* y) {
for(int i = 0; i < n; i++) y[i] = x[i] + 1;
}
// [[Rcpp::export]]
NumericVector cppfunction(NumericVector x){
NumericVector y(x.size());
cfunction(REAL(x), x.size(), REAL(y));
return y;
}
/*** R
x <- c(1, 2, 3, 4)
cppfunction(x)
## [1] 2 3 4 5
*/
If you want to return NumericMatrix
, then assuming the length x
is integer square root:
#include <Rcpp.h>
using namespace Rcpp;
void cfunction(double* x, int n, double* y) {
for(int i = 0; i < n; i++) y[i] = x[i] + 1;
}
// [[Rcpp::export]]
NumericMatrix cppfunctionM(NumericVector x){
int n = sqrt(x.size());
NumericMatrix y(n, n);
cfunction(REAL(x), x.size(), REAL(y));
return y;
}
/*** R
x <- c(1, 2, 3, 4)
cppfunctionM(x)
## [,1] [,2]
## [1,] 2 4
## [2,] 3 5
*/
source to share