可靠地检索分位数函数的反函数

dav*_*and 9 r percentile quantile ecdf

我已经阅读了其他文章(例如here),以获得分位数的“反向”-即,获得与一系列值中的某个值相对应的百分位数。

但是,对于相同的数据序列,答案并不能为我提供与分位数相同的值。

我还研究了分位数提供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
Run Code Online (Sandbox Code Playgroud)

Chr*_*oph 2

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

\n\n
# Simple data\nx = 0:10\np0 = 0.5\n\n# Get value corresponding to a percentile using quantile\nsapply(c(1:7), function(i) quantile(x, p0, type = i))\n# 50% 50% 50% 50% 50% 50% 50% \n# 5.0 5.0 5.0 4.5 5.0 5.0 5.0 \n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
# Get percentile corresponding to a value using ecdf function\ndebug(ecdf)\nmy_ecdf <- ecdf(x)\n
Run Code Online (Sandbox Code Playgroud)\n\n

关键部分是

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

之后你可以检查

\n\n
data.frame(x = vals, y = round(cumsum(tabulate(match(x, vals)))/n, 3), stringsAsFactors = FALSE)\n
Run Code Online (Sandbox Code Playgroud)\n\n

当你除以n=11结果时并不奇怪。如前所述,对于理论,请查看其他答案。

\n\n

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

\n\n
plot(my_ecdf)\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n

在此输入图像描述

\n\n

在此输入图像描述

\n\n

在此输入图像描述

\n\n

广义逆的一个很好的参考:Paul Embrechts,Marius Hofert:“关于广义逆的注释”,Math Meth Oper Res (2013) 77:423\xe2\x80\x93432 DOI

\n