简体   繁体   中英

Rcpp: Returning C array as NumericMatrix 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 have to manually convert the vector outputR to matrix in R. I could of course also make outputR to NumericMatrix (or can I?) and then return that but my real question is that is the above procedure optimal? Do I have to convert output first to std::vector and then NumericVector/Matrix or can I somehow avoid that? I tried wrapping output directly but that didn't work.

Put this in a file, cppfunction.cpp , and run it via library(Rcpp); sourceCpp("cppfunction.cpp") library(Rcpp); sourceCpp("cppfunction.cpp") . Since cfunction was not provided we provide one which 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 a NumericMatrix then assuming that the length of x has an 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
*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM