Rcpp:将 C 数组作为 NumericMatrix 返回给 R

Rcpp: Returning C array as NumericMatrix to R

本文关键字:NumericMatrix 返回 数组 Rcpp      更新时间:2023-10-16
#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);
}

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

把它放在一个文件中,cppfunction.cpp ,然后通过 library(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
*/