11

我已经阅读了关于获取分位数“反向”的其他帖子(例如此处) - 即获取与一系列值中的某个值相对应的百分位数。

但是,对于相同的数据系列,答案并没有给我与分位数相同的值。

我还研究了分位数提供了 9 种不同的算法来计算百分位数。

所以我的问题是:有没有一种可靠的方法来获得分位数函数的反转?ecdf 不采用“类型”参数,因此似乎无法确保它们使用相同的方法。

可重现的例子:

# Simple data
x = 0:10
pcntile = 0.5


# Get value corresponding to a percentile using quantile
(pcntile_value <- quantile(x, pcntile))     

# 50%    
# 5               # returns 5 as expected for 50% percentile     



# Get percentile corresponding to a value using ecdf function
(pcntile_rev <- ecdf(x)(5))                


# [1] 0.5454545   #returns 54.54% as the percentile for the value 5


# Not the same answer as quantile produces
4

2 回答 2

2

链接中的答案非常好,但也许有帮助,看看ecdf 只需运行以下代码:

# Simple data
x = 0:10
p0 = 0.5

# Get value corresponding to a percentile using quantile
sapply(c(1:7), function(i) quantile(x, p0, type = i))
# 50% 50% 50% 50% 50% 50% 50% 
# 5.0 5.0 5.0 4.5 5.0 5.0 5.0 

因此,这不是类型的问题。您可以使用调试单步执行该功能:

# Get percentile corresponding to a value using ecdf function
debug(ecdf)
my_ecdf <- ecdf(x)

关键的部分是

rval <- approxfun(vals, cumsum(tabulate(match(x, vals)))/n, 
    method = "constant", yleft = 0, yright = 1, f = 0, ties = "ordered")

在此之后,您可以检查

data.frame(x = vals, y = round(cumsum(tabulate(match(x, vals)))/n, 3), stringsAsFactors = FALSE)

正如您根据n=11结果划分的那样,这并不奇怪。如前所述,对于理论,请查看其他答案。

顺便说一句,您还可以绘制函数

plot(my_ecdf)

关于你的评论。我认为这不是可靠性问题,而是如何定义“逆分布函数,如果它不存在”的问题:

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

广义逆的一个很好的参考:Paul Embrechts,Marius Hofert:“A note on generalized inverses”,Math Meth Oper Res (2013) 77:423–432 DOI

于 2019-06-23T15:08:10.693 回答
1

ecdf在文档中给出公式的结果。

x <- 0:10
Fn <- ecdf(x)

现在,该对象Fn是一个插值阶跃函数。

str(Fn)
#function (v)  
# - attr(*, "class")= chr [1:3] "ecdf" "stepfun" "function"
# - attr(*, "call")= language ecdf(x)

它保留原始x值和相应的y值。

environment(Fn)$x
# [1]  0  1  2  3  4  5  6  7  8  9 10

environment(Fn)$y
# [1] 0.09090909 0.18181818 0.27272727 0.36363636 0.45454545 0.54545455
# [7] 0.63636364 0.72727273 0.81818182 0.90909091 1.00000000

后者与文档所说的用于计算它们的公式的结果完全相同。来自help('ecdf')

对于观测值 x= (x1,x2, ... xn),Fn 是
小于或等于 t 的观测值的分数,即,

Fn(t) = #{xi <= t}/n = 1/n sum(i=1,n) 指标(xi <= t)。

而不是1:length(x)我将使用seq_along.

seq_along(x)/length(x)
# [1] 0.09090909 0.18181818 0.27272727 0.36363636 0.45454545 0.54545455
# [7] 0.63636364 0.72727273 0.81818182 0.90909091 1.00000000
Fn(x)
# [1] 0.09090909 0.18181818 0.27272727 0.36363636 0.45454545 0.54545455
# [7] 0.63636364 0.72727273 0.81818182 0.90909091 1.00000000
于 2019-06-23T15:01:05.380 回答