使用Rcpp Sugar将均值和标准差传递给dnorm()

cab*_*rke 3 r rcpp

我正在将一些R代码转换为Rcpp代码,并且需要在给定平均值的矢量和标准偏差的矢量的情况下计算观测矢量的可能性.如果我假设均值为0且标准偏差为1,我可以编写此函数(运行此函数需要加载'inline'和'Rcpp'包),

dtest1 = cxxfunction(signature( x = "numeric"),
                      'Rcpp::NumericVector xx(x);
                       return::wrap(dnorm(xx, 0.0, 1.0));', 
                       plugin='Rcpp')
Run Code Online (Sandbox Code Playgroud)

结果如预期.

> dtest1(1:3) 
[1] 0.241970725 0.053990967 0.004431848
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试制作一个功能

dtest2 = cxxfunction(signature( x = "numeric", y="numeric", z="numeric" ),
                  'Rcpp::NumericVector xx(x);
                   Rcpp::NumericVector yy(y);
                   Rcpp::NumericVector zz(z);
                   return::wrap(dnorm(xx, yy, zz));',
                   plugin='Rcpp')
Run Code Online (Sandbox Code Playgroud)

这将允许我通过不同的手段和标准偏差导致错误,如下所示.有没有办法制作我想要的功能,或者我需要手动编程正常密度?

错误

Error in compileCode(f, code, language = language, verbose = verbose) :   
    Compilation ERROR, function(s)/method(s) not created! file31c82bff9d7c.cpp: In function ‘SEXPREC* file31c82bff9d7c(SEXP, SEXP, SEXP)’:
file31c82bff9d7c.cpp:33:53: error: no matching function for call to 
     ‘dnorm4(Rcpp::NumericVector&, Rcpp::NumericVector&, Rcpp::NumericVector&)’
file31c82bff9d7c.cpp:33:53: note: candidates are:
/home/chris/R/x86_64-pc-linux-gnu-library/3.0/Rcpp/include/Rcpp/stats/norm.h:106:1: 
     note: template<int RTYPE, bool NA, class T> Rcpp::stats::D0<RTYPE, NA, T> Rcpp::dnorm4(const Rcpp::VectorBase<RTYPE, NA, VECTOR>&, bool)
/home/chris/R/x86_64-pc-linux-gnu-library/3.0/Rcpp/include/Rcpp/stats/norm.h:107:1: 
     note: template<int RTYPE, bool NA, class T> Rcpp::stats::D1<RTYPE, NA, T> Rcpp::dnorm4(const Rcpp::VectorBase<RTYPE, NA, VECTOR>&, double, bool)
/home/chris/R/x86_64-pc-linux-gnu-library/3.0/Rcpp/include/Rcpp/stats/norm.h:108:1: 
     note: template<int RTYPE, bool NA, class T> Rcpp::stats::D2<RTYPE, NA, T> Rcpp::dnorm4(const Rcpp::VectorBase<RTYPE, NA,
In addition: Warning message:
running command '/usr/lib/R/bin/R CMD SHLIB file31c82bff9d7c.cpp 2> file31c82bff9d7c.cpp.err.txt' had status 1
Run Code Online (Sandbox Code Playgroud)

Rom*_*ois 7

dnorm仅根据第一个参数进行矢量化.

为了简化(稍微涉及一些,但我们不需要在这里关注这个),电话

dnorm(xx, 0.0, 1.0)
Run Code Online (Sandbox Code Playgroud)

使用过载

NumericVector dnorm( NumericVector, double, double )
Run Code Online (Sandbox Code Playgroud)

而第二个电话尝试使用类似的东西

NumericVector dnorm( NumericVector, NumericVector, NumericVector )
Run Code Online (Sandbox Code Playgroud)

这没有实现.我们可以实现它,它必须在我们的优先级列表中足够高.

与此同时,编写一个小包装器很容易(比如不处理参数长度等):

NumericVector my_dnorm( NumericVector x, NumericVector means, NumericVector sds){
    int n = x.size() ;
    NumericVector res(n) ;
    for( int i=0; i<n; i++) res[i] = R::dnorm( x[i], means[i], sds[i] ) ;
    return res ;
}
Run Code Online (Sandbox Code Playgroud)