Reputation: 31
I am trying to use Rcpp for the first time. I have made a script in C++ that works fine independently of R, but when trying to implement it in Rcpp I am getting an error message about the return type. Here is the gist of what I've done:
cppSim <- '
#include <iostream>
#include <random>
#include <math.h>
//[[Rcpp::plugins(cpp11)]]
#include <Rcpp.h>
#include <cmath>
#include <iomanip>
#include <boost/math/distributions/students_t.hpp>
using boost::math::students_t;
using namespace std;
using namespace Rcpp;
// function to calculate p-value from a t-test
double ttestPValue(vector<double> obs1, vector<double> obs2, int nSamples){
...
return(q); \\ q is a double, this bit works fine
}
NumericVector powerSimulation(int nSamples, int meanDiff, int nPerm, double pValueCutOff){
...
// create vectors to hold data
double sim1T[totalRD][nPerm];
...
sim1T[rdmu - minRD][j] = ttestPValue(obs1, obs2, nSamples);
double power[totalRD];
for (int j = 0; j < 100; j++){
power[j] = 0;
}
for (int i = 0; i < totalRD; i++){
for (int sum = 0; sum < nPerm; sum ++){
if (sim1T[i][sum] < pValueCutOff){
power[i] = power[i] + 1;
}
}
power[i] = (power[i] / nPerm)*100;
}
return power;
}'
To run it I am using:
settings=getPlugin("Rcpp")
settings$env$PKG_CXXFLAGS=paste('-std=c++11',settings$env$PKG_CXXFLAGS,sep=' ')
simRcpp <- cxxfunction(signature(nSamplesR = "int", meanDiffR = "int", nPermR = "int", pValueCutOffR = "double"),
plugin="Rcpp",
settings = settings,
includes = cppSim,
body='
int nSamples = Rcpp::as<int>(nSamplesR);
int meanDiff = Rcpp::as<int>(meanDiffR);
int nPerm = Rcpp::as<int>(nPermR);
double pValueCutOff = Rcpp::as<double>(pValueCutOffR);
return Rcpp::wrap( cppSim(nSamples, meanDiff, nPerm, pValueCutOff));')
The error that I'm getting is:
file928498473e2.cpp: In function ‘Rcpp::NumericVector powerSimulation(int, int, int, double)’:
file928498473e2.cpp:165:8: error: invalid conversion from ‘double*’ to ‘const int&’ [-fpermissive]
return power;
^
I get that my return type for power is wrong but how do I make it right? I've tried wrapping it as a NumericVector but that doesn't seem to work and I can't find an example with the same issue, as not everyone uses cxxfunction().
Upvotes: 0
Views: 351
Reputation: 522
Please change
double power[totalRD];
into
std::vector<double> power(totalRD);
Upvotes: 0