Rcpp: Returning C array as NumericMatrix to R

丶灬走出姿态 提交于 2019-12-18 18:02:11

问题


#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.


回答1:


Put this in a file, cppfunction.cpp, and run it via 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
*/


来源:https://stackoverflow.com/questions/26194225/rcpp-returning-c-array-as-numericmatrix-to-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!