c – Rcpp:将C数组作为NumericMatrix返回到R

c – Rcpp:将C数组作为NumericMatrix返回到R,第1张

概述#include <Rcpp.h>#include <vector>extern "C"{ #include "cheader.h"}using namespace Rcpp;// [[Rcpp::export]]NumericVector cppfunction(NumericVector inputR){ double const* input = inputR.
#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;}/*** Rx <- c(1,2,3,4)cppfunction(x)## [1] 2 3 4 5*/

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

#include <Rcpp.h>using namespace Rcpp;voID cfunction(double* x,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),4)cppfunctionM(x)##      [,1] [,2]## [1,]    2    4## [2,]    3    5*/
总结

以上是内存溢出为你收集整理的c – Rcpp:将C数组作为NumericMatrix返回到R全部内容,希望文章能够帮你解决c – Rcpp:将C数组作为NumericMatrix返回到R所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1216309.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-05
下一篇2022-06-05

发表评论

登录后才能评论

评论列表(0条)

    保存