2015-10-14 59 views
1

我基本上试图使用Rcpp将一些R代码翻译为cpp。我在下面的代码以下错误:无法将Rcpp :: sugar :: Plus_Vector_Primitive转换为Rcpp :: traits :: storage_type

error: cannot convert ‘Rcpp::sugar::Plus_Vector_Primitive<14, true, Rcpp::stats::D2<14, true, Rcpp::Vector<14, Rcpp::PreserveStorage> > >’ to ‘Rcpp::traits::storage_type<14>::type {aka double}’ in assignment 

下面是代码

#include <RcppArmadillo.h> 
#include <Rcpp.h> 

using namespace Rcpp; 

// [[Rcpp::depends(RcppArmadillo)]] 

// [[Rcpp::export(".loop_exp")]] 
void mm_mult(const arma::vec& helpa, const arma::mat& helpb, const arma::vec& helpc, 
      const Rcpp::NumericVector& t1, const arma::vec& t2, int J, Rcpp::NumericVector& prob) 
{ 
    int j; 
    for (j = 1; J <= J; j++) 
    { 
    arma::mat t = (helpb.row(j)).t() * (t2); 
    double tt = t[0,0]; 
    prob[j] = (helpa[j] + dnorm(t1, tt, helpc[j])); <---- here is the error 
    } 

    return; 
} 

我想这是一个类型转换错误,但基本上我不能找到一个很好的参考..谁能给我在这个问题上的一些帮助?非常感谢!

回答

3

原因是dnorm“合成糖”有一个签名NumericVector dnorm(NumericVector, double, double)

由于它返回NumericVector,您必须自己将其转换为double值。

一个快速简单的方法是将返回的矢量集合起来,以获得其第一个元素。在您的例子:

prob[j] = (helpa[j] + dnorm(t1, tt, helpc[j])[0]); // Note the "[0]" 

否则,有一对夫妇在你的代码的其他潜在的问题:你不应该#include <Rcpp.h>,因为它已经与#include <RcppArmadillo.h> ---也,你的循环结束条件,J <= J,看起来做可疑我...

希望这有助于:)

+0

虽然这解决了编译错误,更多地考虑它,你大概的意思是存储'J-th'元素,无论是'概率[ j] =(helpa [j] + dnorm(t1,tt,helpc [j])[j]);'或'prob [j] =(helpa [j] + dnorm(t1 [j],tt,helpc [ j])[0]);' – Jealie

+2

另一种方法是由'R'命名空间中的_scalar_变体提供:'R :: dnorm()' - 参见文件'Rmath.h'。 –