rcpp不确定应该返回什么类。错误:双精度无法转换为const int&

时间:2019-03-20 13:46:03

标签: c++ r rcpp

我正在尝试第一次使用Rcpp。我用C ++编写了一个脚本,该脚本可以独立于R正常运行,但是当尝试在Rcpp中实现该脚本时,我收到有关返回类型的错误消息。这是我所做的要点:

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; 
}'

要运行它,我正在使用:

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));')

我得到的错误是:

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;
        ^

我得到我的功率返回类型错误,但是如何正确设置呢?我曾尝试将其包装为NumericVector,但这似乎不起作用,并且我找不到具有相同问题的示例,因为不是每个人都使用cxxfunction()。

1 个答案:

答案 0 :(得分:0)

请更改

double power[totalRD];

进入

std::vector<double> power(totalRD);