Rcpp分位数实现 [英] Rcpp quantile implementation

查看:34
本文介绍了Rcpp分位数实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 NumericVector x 的 Rcpp double.我想在 Rcpp 代码流中获得此类 x 的 .95 分位数.我不知道我怎样才能得到它.是否有 RcppArmadillo 实现?

I have a Rcpp double containing a NumericVector x. I would like to get the .95 quantile of such x within the Rcpp code flow. I do not know how can I get it. Is there an RcppArmadillo implementation?

推荐答案

我不是 Rcpp 专家,我的功能可能需要很多改进,但似乎您可以轻松创建自己的Rcpp 分位数函数(由于偏斜的可能性很大,并且在非整数索引上存在索引问题,因此在小向量上不太准确,但随着向量的增长而改进)

I'm not a Rcpp expert and my function probably needs lots of improvement, but it seems that you can easily create your own Rcpp quantile function (which will be not so accurate on small vectors due to high chance to skewness and problems with indexing on non-integer indexes, but improves as the vector grows)

library(Rcpp) # You can use sourceCpp() instead of cppFunction if you wish
cppFunction('NumericVector Cquantile(NumericVector x, NumericVector q) {
  NumericVector y = clone(x);
  std::sort(y.begin(), y.end());
  return y[x.size()*(q - 0.000000001)];
}')

1e+3 向量上测试

set.seed(123)
y <- rnorm(1000)
qs <- seq(0, 100, 25)/100

quantile(y, qs)
#           0%          25%          50%          75%         100% 
# -2.809774679 -0.628324243  0.009209639  0.664601867  3.241039935 


setNames(Cquantile(y, qs), paste0(qs * 100, "%"))
#          0%         25%         50%         75%        100% 
# -2.80977468 -0.62957874  0.00729009  0.66441586  3.24103993 

看起来足够接近.所以我们的向量 y 的 95% 分位数是

Looks close enough. So the 95% quantile for our vector y would be

Cquantile(y, .95)
## [1] 1.675697

<小时>

还有一些用于已知分布的糖分位数函数,例如正态分布、伽马分布等,可以替代使用,请参阅 这里 一些例子.

这篇关于Rcpp分位数实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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