从R,我正在尝试运行sourceCpp此文件:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace arma;
using namespace Rcpp;
// [[Rcpp::export]]
vec dnormLog(vec x, vec means, vec sds) {
int n = x.size();
vec res(n);
for(int i = 0; i < n; i++) {
res[i] = log(dnorm(x[i], means[i], sds[i]));
}
return res;
}
Run Code Online (Sandbox Code Playgroud)
看到这个答案,看看我从哪里获得了这个功能.这会引发错误:
no matching function for call to 'dnorm4'
这是我希望通过使用循环来防止的确切错误,因为引用的答案提到dnorm仅针对其第一个参数进行向量化.我担心答案是显而易见的,但我尝试R::在之前添加dnorm,尝试使用NumericVector而不是在前面vec使用log().没运气.但是,R::之前添加dnorm会产生单独的错误:
too few arguments to function call, expected 4, have 3; did you mean '::dnorm4'?
Run Code Online (Sandbox Code Playgroud)
这是不通过更换固定dnorm以上R::dnorm4.
这里有两个很好的教育时刻:
R::dnorm().这是一个修复版本,包括你可能会感兴趣的第二个变种:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
arma::vec dnormLog(arma::vec x, arma::vec means, arma::vec sds) {
int n = x.size();
arma::vec res(n);
for(int i = 0; i < n; i++) {
res[i] = std::log(R::dnorm(x[i], means[i], sds[i], FALSE));
}
return res;
}
// [[Rcpp::export]]
arma::vec dnormLog2(arma::vec x, arma::vec means, arma::vec sds) {
int n = x.size();
arma::vec res(n);
for(int i = 0; i < n; i++) {
res[i] = R::dnorm(x[i], means[i], sds[i], TRUE);
}
return res;
}
/*** R
dnormLog( c(0.1,0.2,0.3), rep(0.0, 3), rep(1.0, 3))
dnormLog2(c(0.1,0.2,0.3), rep(0.0, 3), rep(1.0, 3))
*/
Run Code Online (Sandbox Code Playgroud)
当我们获取它时,两者都返回相同的结果,因为R API允许我们要求取对数.
R> sourceCpp("/tmp/dnorm.cpp")
R> dnormLog( c(0.1,0.2,0.3), rep(0.0, 3), rep(1.0, 3))
[,1]
[1,] -0.923939
[2,] -0.938939
[3,] -0.963939
R> dnormLog2(c(0.1,0.2,0.3), rep(0.0, 3), rep(1.0, 3))
[,1]
[1,] -0.923939
[2,] -0.938939
[3,] -0.963939
R>
Run Code Online (Sandbox Code Playgroud)