我对如何使用 Rcpp 编写 R 使用的默认分位数方法很感兴趣。这里有一个基本的解决方案Rcpp quantile implementation .如解决方案中所述,它不适用于小向量。
但是,我真的很想实现基础 R(类型 7 方法),如图所示 https://svn.r-project.org/R/trunk/src/library/stats/R/quantile.R
基本代码如下:
x <- 1:100 # make a test vector
probs <- c(0.05, 0.95)
n <- length)x)
# R code
index <- 1 + (n - 1) * probs
lo <- floor(index)
hi <- ceiling(index)
x <- sort(x, partial = unique(c(lo, hi)))
qs <- x[lo]
i <- which(index > lo)
h <- (index - lo)[i] # > 0 by construction
qs[i] <- (1 - h) * qs[i] + h * x[hi[i]]
例如给出:
quantile(1:100, probs = c(0.05, 0.95))
5% 95%
5.95 95.05
了解您如何使用 Rcpp 来解决这个问题真的很有帮助。我使用 RStudio 并习惯于运行更简单的 Rcpp 代码,但我坚持使用这个代码。
如有任何帮助,我们将不胜感激。
谢谢
大卫
最佳答案
像这样在 Rcpp 中调用 R 的 quantile
函数怎么样?
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector quantileCpp(NumericVector x, NumericVector probs) {
Environment stats("package:stats");
Function quantile = stats["quantile"];
int npr = probs.size();
NumericVector ans(npr);
for(int i=0; i<npr; i++){
ans[i] = as<double>(quantile(x, probs[i]));
}
return ans;
}
将代码保存为“quantileCpp.cpp”并运行:
> Rcpp::sourceCpp('quantileCpp.cpp')
> quantileCpp(1:100,c(0.05,0.95))
[1] 5.95 95.05
> quantile(1:100,c(0.05,0.95))
5% 95%
5.95 95.05
我知道这不是最快的解决方案(就计算时间而言),但却是我能想到的最简单的解决方案。
关于使用 Rcpp 的 R 分位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28222850/