【问题标题】:Sampling from a specific part of a normal distribution in R从 R 中正态分布的特定部分采样
【发布时间】:2019-01-19 17:58:19
【问题描述】:

我试图首先从mother 正态分布中提取所有值<= -4(称为p1)。然后,根据它们在mother 中被选中的概率,随机抽取p1s 中的50 个进行替换(将这50 个称为p2)。例如,-4-6 更可能被选中,后者更靠近尾部区域。

我想知道下面的 R 代码是否正确捕获了我上面描述的内容?

mother <- rnorm(1e6)
p1 <- mother[mother <= -4]
p2 <- sample(p1, 50, replace = T) # How can I define probability of being selected here?

【问题讨论】:

    标签: r random sampling resampling


    【解决方案1】:

    您可以使用函数sample 参数prob。引用help("sample"):

    prob 用于获得元素的概率权重向量 被采样的向量。

    Details部分:

    可选的 prob 参数可用于给出权重向量 获取被采样向量的元素。他们不需要总和 为一,但它们应该是非负的,而不是全为零。

    所以你必须小心,离平均值越远概率越小,正态分布会很快下降到小概率值。

    set.seed(1315)    # Make the results reproducible
    
    mother <- rnorm(1e6)
    p1 <- mother[mother <= -4]
    
    p2 <- sample(p1, 50, replace = T, prob = pnorm(p1))
    

    您可以看到它与直方图一起使用。

    hist(p2)
    

    【讨论】:

    • @rnorouzian 矿假设正态分布,TUSHAr 使用均匀分布。
    • @rnorouzian 我遇到了一个错误,Error in sample.int(length(x), size, replace, prob) : incorrect number of probabilities
    • @rnorouzian 是的,对于示例数据集,mean(p1) 返回[1] -4.208714mean(p2) 返回[1] -4.125671
    • @rnorouzian 是的,它会的。 sd越大,效果越大。
    • 我认为这种方法不能正确地从正态分布中采样(以 x p1 应该已经反映 -5 p1 再次采样,使用 pdf(x) 作为采样权重,您可以将差异加倍,夸大它。
    【解决方案2】:

    首先从截断正态分布中采样不是更容易吗?

    truncnorm::rtruncnorm(50, a = -Inf, b = -4)
    

    【讨论】:

      【解决方案3】:

      我认为您正在寻找这样的东西:

      mother <- rnorm(1e6)
      p1 <- mother[mother <= -4]
      

      计算p1从mother中被选中的概率

      p2 <- sample(p1, 50, replace = T,prob = pnorm(p1,mean = mean(mother),sd = sd(mother)))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-18
        • 2020-06-03
        • 1970-01-01
        • 1970-01-01
        • 2013-12-20
        • 1970-01-01
        • 1970-01-01
        • 2018-05-22
        相关资源
        最近更新 更多