【问题标题】:How to calculate the overlap between 2 dataset distribution如何计算2个数据集分布之间的重叠
【发布时间】:2021-03-01 02:18:57
【问题描述】:

嗨,如何计算 R 中 2 列(或列的 2 个子集)之间的重叠区域。 请看下面的示例数据:

set.seed(1234)
df <- data.frame(
  Data=factor(rep(c("D1", "D2"), each=200)),
  weight=round(c(rnorm(200, mean=55, sd=5),
                 rnorm(200, mean=65, sd=5)))
)

library(ggplot2)
plot <- ggplot(df, aes(weight,fill = Data))+
  geom_density() 
plot

这导致了下图。我想知道,如何为重叠区域着色并计算重叠系数(OVL),类似于 here 使用蒙特卡洛积分所做的事情? 请注意,在我询问我是否有观测值数据集时,提供的链接(和上面的示例)使用了参数分布。

【问题讨论】:

    标签: r integration montecarlo


    【解决方案1】:

    我通常发现直接处理密度并将它们绘制为geom_area 更容易。如果您让 x 轴采样点在两个分布上匹配,您可以使用 pmin 找到重叠区域,其值的总和除以两条曲线的值的总和应该会给您重叠的总面积。

    d1dens <- with(df, density(weight[Data == "D1"], 
                               from = min(weight), 
                               to = max(weight)))
    d2dens <- with(df, density(weight[Data == "D2"], 
                               from = min(weight),
                               to = max(weight)))
    joint <- pmin(d1dens$y, d2dens$y)
    
    df2 <- data.frame(x = rep(d1dens$x, 3), 
                      y = c(d1dens$y, d2dens$y, joint),
                      Data = rep(c("D1", "D2", "overlap"), each = length(d1dens$x)))
    
    ggplot(df2, aes(x, y, fill = Data)) + 
      geom_area(position = position_identity(), color = "black") +
      scale_fill_brewer(palette = "Pastel2") +
      theme_bw()
    

    sum(joint) / sum(d1dens$y, d2dens$y)
    #> [1] 0.1480701
    

    【讨论】:

    • 非常感谢您的回复。一条评论,对于重叠系数的计算,不会是(sum(joint)/sum(d1dens$y) + sum(joint)/sum(d2dens$y))/2
    猜你喜欢
    • 2014-09-29
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 2021-05-26
    • 2021-10-13
    相关资源
    最近更新 更多