Using dnorm with RcppArmadillo

后端 未结 1 1373
无人共我
无人共我 2020-12-11 08:06

From R, I\'m trying to run sourceCpp on this file:

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

using name         


        
相关标签:
1条回答
  • 2020-12-11 08:58

    There are two nice teachable moments here:

    1. Pay attention to namespaces. If in doubt, don't go global.
    2. Check the headers for the actual definitions. You missed the fourth argument in the scalar version R::dnorm().

    Here is a repaired version, included is a second variant you may find interesting:

    #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))
    */
    

    When we source this, both return the same result because the R API allows us to ask for logarithms to be taken.

    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> 
    
    0 讨论(0)
提交回复
热议问题