Rcpp quantile implementation

懵懂的女人 提交于 2019-12-05 22:20:49

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)];
}')

Testing on 1e+3 vector

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 

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

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

There are also some Sugar quantile functions for knows distributions such normal, gamma, etc. that can be used instead, see here for some examples.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!