#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);
}
Run Code Online (Sandbox Code Playgroud)
这是有效的,除了我必须手动将矢量outputR转换为R中的矩阵.我当然也可以将outputR转换为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
*/
Run Code Online (Sandbox Code Playgroud)
如果你想返回a 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
*/
Run Code Online (Sandbox Code Playgroud)