使用 Rmath.h 中的 pnorm 和 Rcpp [英] Use pnorm from Rmath.h with Rcpp

查看:30
本文介绍了使用 Rmath.h 中的 pnorm 和 Rcpp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 pnorm 和 qnorm 等函数使用 Rcpp 编写一段 C++ 代码.我可以将这些的 Rcpp 糖版本用于矢量,如 https://stackoverflow.com/a/9738848/567015,但我不需要在向量上执行此操作,而只需在双精度上执行此操作.

I am trying to write a piece of C++ code with Rcpp using functions like pnorm and qnorm. I can use the Rcpp sugar versions of these for vectors as explained in https://stackoverflow.com/a/9738848/567015, but I don't need to do this on a vector but just on a double.

如果我理解正确,我可以使用 Rf_ 前缀从 Rmath.h 获取标量版本.但是,Rf_pnorm 不起作用:

If I understand correctly I can use the Rf_ prefix to get the scalar versions from Rmath.h. However, Rf_pnorm doesn't work:

library("inline")
Src <-  '
double y = as<double>(x);
double res = Rf_pnorm(y,0.0,1.0);
return wrap(res) ;
'

fx <- cxxfunction( signature(x = "numeric") ,Src, plugin = "Rcpp" )

fx(1)

作为错误给出:

file10c81a585dee.cpp: In function 'SEXPREC* file10c81a585dee(SEXP)':
file10c81a585dee.cpp:32:32: error: 'Rf_pnorm' was not declared in this scope

经过一些谷歌搜索和反复试验,我发现 Rf_pnorm5 确实有效,但需要额外的参数来降低尾数和对数比例:

I found after some googling and trial and error that Rf_pnorm5 does work but requires extra parameters for lower tail and log scale:

Src <-  '
double y = as<double>(x);
double res = Rf_pnorm5(y,0.0,1.0,1,0);
return wrap(res) ;
'

fx <- cxxfunction( signature(x = "numeric") ,Src, plugin = "Rcpp" )

fx(1)
## [1] 0.8413447

很好,但我不明白为什么这有效但 Rf_pnorm 没有.我宁愿使用 Rf_pnorm,因为我认为这样可以更容易地为不同的分布找到正确的代码.

Great, but I don't understand why this works but Rf_pnorm doesn't. I rather use Rf_pnorm because I think that makes it easier to find the right codes for different distributions.

推荐答案

这里是 Rcpp 糖变体,它与 Rcpp 更自然:

Here is the Rcpp sugar variant which is more natural with Rcpp:

R> library(inline)
R> 
R> Src <- '
+ NumericVector y = NumericVector(x);
+ NumericVector res = pnorm(y,0.0,1.0);
+ return res;
+ '
R> 
R> fx <-  cxxfunction( signature(x = "numeric") , body=Src, plugin = "Rcpp")
R> 
R> fx(seq(0.8, 1.2, by=0.1))
[1] 0.788145 0.815940 0.841345 0.864334 0.884930
R> 
R> fx(1.0)      ## can also call with scalar args
[1] 0.841345
R> 

更仔细地查看我们的头文件,我们取消了 Rmath.h 中的 pnorm 等,以便定义您从 Rcpp 糖中获得的(矢量化)变体.

Looking more closely at our headers, we undefine the pnorm et al from Rmath.h in order to define the (vectorised) variants you get from Rcpp sugar.

于 2012-11-14 随着今天发布的 Rcpp 0.10.0,您可以调用 do 签名 R::pnorm(double, double, double, int, int) 如果您想使用针对 Rmath.h 编写的 C 风格代码.Rcpp 糖仍然为您提供矢量化版本.

Edit on 2012-11-14: With Rcpp 0.10.0 released today, you can call do the signature R::pnorm(double, double, double, int, int) if you want to use C-style code written against Rmath.h. Rcpp sugar still gives you vectorised versions.

这篇关于使用 Rmath.h 中的 pnorm 和 Rcpp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆