简体   繁体   English

R分位数使用Rcpp

[英]R quantile using Rcpp

I'm interested in how to go about coding the default quantile method used by R using Rcpp. 我对如何使用Rcpp编写R使用的默认分位数方法感兴趣。 There is a basic solution here Rcpp quantile implementation . 这里有一个基本的解决方案Rcpp分位数实现 As noted in the solution it won't work as well for small vectors. 如解决方案中所述,它对于小向量也不会起作用。

However, I would really like to implement the base R (type 7 method), shown here https://svn.r-project.org/R/trunk/src/library/stats/R/quantile.R 但是,我真的想实现基本R(类型7方法),这里显示https://svn.r-project.org/R/trunk/src/library/stats/R/quantile.R

The basic code looks like: 基本代码如下:

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]]

which, for example gives: 例如,它给出:

quantile(1:100, probs = c(0.05, 0.95))
5%   95% 
5.95 95.05 

It would really help to see how you approach this using Rcpp. 看看你如何使用Rcpp来解决这个问题真的很有帮助。 I use RStudio and am used to running simpler Rcpp code, but I am stuck on this one. 我使用RStudio并用于运行更简单的Rcpp代码,但我坚持这个。

Any help would be much appreciated. 任何帮助将非常感激。

Thanks 谢谢

David 大卫

What about calling the quantile function of R within Rcpp like this? 如何在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;
}

save the code as 'quantileCpp.cpp' and run: 将代码保存为'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 

I know is not the fastest solution (in terms of computational time), but is the easiest solution I can think off. 我知道这不是最快的解决方案(就计算时间而言),但这是我能想到的最简单的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM