为什么我在Rcpp中使用"pnorm"会出现错误

los*_*est 2 r armadillo rcpp

我需要arma::在我的Rcpp代码中包含变量.但是在尝试使用糖功能时遇到了问题pnorm.这是一个演示:

#include <RcppArmadillo.h>
#include <RcppArmadilloExtensions/sample.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;

// [[Rcpp::export]]
double pget(NumericVector x, NumericVector beta) {
  arma::colvec xx = Rcpp::as<arma::colvec>(x) ;
  arma::colvec bb = Rcpp::as<arma::colvec>(beta) ;
  double tt = as_scalar( arma::trans(xx) * bb);
  double temp = Rcpp::pnorm(tt);
  return temp;
}
Run Code Online (Sandbox Code Playgroud)

然后我收到一个错误: no matching function for call to 'pnorm5'

这是否意味着我不能使用Rcpp::pnorm???

Ral*_*ner 6

所述Rcpp糖函数用于矢量类型参数等Rcpp::NumericVector.对于标量参数,您可以使用R命名空间中的函数:

#include <RcppArmadillo.h>
#include <RcppArmadilloExtensions/sample.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;

// [[Rcpp::export]]
double pget(NumericVector x, NumericVector beta) {
  arma::colvec xx = Rcpp::as<arma::colvec>(x) ;
  arma::colvec bb = Rcpp::as<arma::colvec>(beta) ;
  double tt = as_scalar( arma::trans(xx) * bb);
  double temp = R::pnorm(tt, 0.0, 1.0, 1, 0);
  return temp;
}

/*** R
x <- rnorm(5)
beta <- rnorm(5)
pget(x, beta)
*/
Run Code Online (Sandbox Code Playgroud)

BTW,这里有两个变种.第一个变体使用arma而不是Rcpp向量作为参数.由于这些是const引用,因此不会复制任何数据.另外,arma::dot用于:

// [[Rcpp::export]]
double pget2(const arma::colvec& xx, const arma::colvec& bb) {
  double tt = arma::dot(xx, bb);
  return R::pnorm(tt, 0.0, 1.0, 1, 0);
}
Run Code Online (Sandbox Code Playgroud)

第二个变体计算标量积而不求助于Armadillo:

// [[Rcpp::export]]
double pget3(NumericVector x, NumericVector beta) {
  double tt = Rcpp::sum(x * beta);
  return R::pnorm(tt, 0.0, 1.0, 1, 0);
}
Run Code Online (Sandbox Code Playgroud)

  • 在解决OP的问题方面有很好的答案(+1),但是关于你发布的代码的注释:你的参数顺序混合了一点.你想要`R :: pnorm(tt,0.0,1.0,1,0)`而不是`R :: pnorm(tt,1.0,0.0,1,0)`(均值在sd之前). (2认同)
  • 不是'as_scalar(arma :: trans(xx)*bb)`相当于更短的`dot(xx,bb)`?([文档】(http://arma.sourceforge.net/docs.html#dot)) (2认同)