c++ - 将 dnorm 与 RcppArmadillo 结合使用

标签 c++ r rcpp

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

参见 this answer看看我从哪里得到这个功能。这会引发错误:

没有匹配函数调用 'dnorm4'

这正是我希望通过使用循环来防止的错误,因为引用的答案提到 dnorm 仅针对其第一个参数进行矢量化。我担心答案很明显,但我尝试在 dnorm 之前添加 R::,尝试使用 NumericVector 而不是 vec ,没有在前面使用log()。没有运气。但是,在 dnorm 之前添加 R:: 确实会产生一个单独的错误:

too few arguments to function call, expected 4, have 3; did you mean '::dnorm4'?

通过将上面的 dnorm 替换为 R::dnorm4 来修复。

最佳答案

这里有两个很好的教学时刻:

  1. 注意命名空间。如果有疑问,请不要走向全局。
  2. 检查标题以了解实际定义。您错过了 标量 版本 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))
*/

当我们获取它时,两者返回相同的结果因为 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> 

关于c++ - 将 dnorm 与 RcppArmadillo 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40031275/

相关文章:

c++ - 如何通过迭代使迭代器表现得像一个类型?

r - 如何在 R-2.14 中使用新的 'ByteCompile' 字段?

r - 如何有效地对 data.table 中的向量列进行操作

r - 将回归线添加到多个散点图

c++ - 使用 Rcpp::IntegerVectors 添加 int

performance - Armadillo 中的高效加权叉积

c++ - 了解 std::transform 以及如何打败它

c++ - 减少 Linux 中的每个线程内存

c++ - 关于C++内联函数的两个问题

javascript - 从 R 中的 finviz 中抓取表格