我正在将一些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')
并且结果如预期。
> dtest1(1:3)
[1] 0.241970725 0.053990967 0.004431848
然而,如果我尝试创建一个函数
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')
我希望能够传入不同的均值和标准差,但是会出现下面显示的错误。有没有办法让我尝试创建的函数生效,或者我需要手动编写正态密度函数?
错误信息
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
dnorm4
函数。(然而,在 Mac 上我也遇到了类似的错误。) - IRTFMdtest = cxxfunction(signature( x = "numeric" ), 'Rcpp::NumericVector xx(x); return::wrap(dnorm(xx, 0, 1));', plugin='Rcpp')
唯一的区别是均值和标准差参数不是十进制形式。 - IRTFM