2014-11-06 57 views
3

我有一个包含NumericVector x的Rcpp double。我想要在Rcpp代码流中获得这样的x的0.95分位数。我不知道我怎么能得到它。是否有RcppArmadillo实现?Rcpp分位数实现

+0

你知道'x'的分布吗?有一些内置的糖函数可以计算每个分布,如'qnorm'等。 – 2014-11-06 18:46:01

+0

x是经验值我需要第 - 百分点 – 2014-11-06 21:14:16

+2

您是否阅读过[this](http://stats.stackexchange.com/questions/) 7358/C的库换统计的计算)? Dirk演示了Boost Math库包含分位数函数。 @DavidArenburg的答案似乎对积分响应很好,但如果你想估计连续的数据,你需要更强大的功能,比如Boost的'quantile()'。 – r2evans 2014-11-06 21:55:50

回答

4

我不是Rcpp专家,我的功能可能需要很多改进,但似乎你可以很容易地创建你自己的Rcpp分位数函数(由于很可能出现偏斜和问题与非整数索引的索引,但提高作为载体的增长)

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%分位数将

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

也有一些糖位数职能知道这样的分布正常,伽马等是可以用来代替,看到here的一些例子。