Rcpp: Returning C array as NumericMatrix to R

余生颓废 提交于 2019-11-30 15:50:01

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

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
*/
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!