RCPP:返回数组c为NumericMatrix至R [英] Rcpp: Returning C array as NumericMatrix to R

查看:773
本文介绍了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 /矩阵或可不知何故,我避免?我试着直接包装产量,但没有奏效。

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.

推荐答案

将这个文件中的 cppfunction.cpp ,并通过运行库(RCPP); sourceCpp(cppfunction.cpp)。由于 cfunction 没有提供我们提供的其中一个加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
*/

如果您想返回一个 NumericMatrix 然后假设的长x 有一个整数的平方根:

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

这篇关于RCPP:返回数组c为NumericMatrix至R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆