如何在 R 中获得两个交叉 ecdf 的交点?

Nmg*_*mgh 1 intersection r cdf ecdf

我有两个使用以下代码的 ecdf 图:

ecdf1 <- ecdf(data1)
ecdf2 <- ecdf(data2)
Run Code Online (Sandbox Code Playgroud)

这些情节相互交叉。我需要获取交叉点(交点)坐标。我应该如何在 R 中执行此操作?

All*_*ron 8

让我们创建一个可重现的示例来演示:

set.seed(1)

data1 <- rnorm(50) + 1.2
data2 <- rexp(50)
Run Code Online (Sandbox Code Playgroud)

现在我们使用您的代码创建两个 ecdf 函数:

ecdf1 <- ecdf(data1)
ecdf2 <- ecdf(data2)
Run Code Online (Sandbox Code Playgroud)

如果我们绘制它们,我们将看到这些曲线在两个点处相交:一次在 0 和 1 之间,一次在 2 之上。

plot(ecdf1, col = "red")
plot(ecdf2, col = "blue", add = TRUE)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

为了找到这些精确点,我们创建一个 x 函数,它是 x 处两个 ecdf 函数之间的差。然后我们使用该函数uniroot来确定该差值函数在哪里等于 0:

diff_func <- function(x) ecdf1(x) - ecdf2(x)

root1 <- uniroot(diff_func, c(0, 1))$root # Finds the lower intersection
root2 <- uniroot(diff_func, c(2, 3))$root # Finds the upper intersection
Run Code Online (Sandbox Code Playgroud)

我们可以检查我们的结果是否有意义:

root1
#> [1] 0.1568627
root2
#> [1] 2.055556
Run Code Online (Sandbox Code Playgroud)

甚至可以用图段来证明交叉点是正确的:

root1
#> [1] 0.1568627
root2
#> [1] 2.055556
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

创建于 2023-02-26,使用reprex v2.0.2