其他分享
首页 > 其他分享> > c – Rcpp:将C数组作为NumericMatrix返回到R

c – Rcpp:将C数组作为NumericMatrix返回到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);
}

这是有效的,除了我必须手动将矢量outputR转换为R中的矩阵.我当然也可以将outputR转换为NumericMatrix(或者我可以?)然后返回,但我真正的问题是上述过程是最优的吗?我是否必须先将输出转换为std :: vector,然后再转换为NumericVector / Matrix,还是可以以某种方式避免这种情况?我试着直接包装输出但是没有用.

解决方法:

把它放在一个文件cppfunction.cpp中,然后通过库(Rcpp)运行它; sourceCpp( “cppfunction.cpp”).由于没有提供cfunction,我们提供了一个为每个输入元素添加1:

#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
*/

如果要返回NumericMatrix,则假设x的长度具有整数平方根:

#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
*/

标签:c-3,c,r,rcpp
来源: https://codeday.me/bug/20190728/1561073.html