【问题标题】:R - Stratified Sampling with Large DatasetR - 大数据集的分层抽样
【发布时间】:2017-11-10 21:27:57
【问题描述】:

我有一个大型数据集,并且我有多个要采样的组。每个组都有一定数量的阳性病例,值为 1,还有更多的阴性病例,值为 0。

对于每个组,我想选择所有阳性病例,然后随机选择等于该组阳性病例数量 4 倍的阴性病例。

我还需要在大量数据上快速运行的东西。

半更新:

stratified_sample = data %>%
    group_by(group) %>%
    mutate(n_pos = sum(response == 1),
           n_neg = 4 * n_pos) %>%
  group_by(group,response) %>%
  mutate(rec_num = n(),
         random_val = runif(n()),
         random_order = rank(random_val)) %>%
    filter(response == 1 | random_order <= n_neg)

【问题讨论】:

标签: r sampling


【解决方案1】:

如果您输入正确的名称,这应该可以工作。如果您有问题,请提供可重现的示例。

library(dplyr)

stratified_sample = your_large_dataset %>%
    group_by(whatever_your_grouping_variable_is) %>%
    mutate(n_pos = sum(column_name_of_your_label == 1),
           n_neg = sum(column_name_of_your_label == 0),
           cutoff = 4 * n_pos / n_neg) %>%
    filter(column_name_of_your_label == 1 | runif(n()) < cutoff)

这使每个负例的概率为 4 * 正例数/要选择的负例数,因此样本分数不会准确,但它具有您想要的预期值。

【讨论】:

  • 你让我非常接近,但根据你如何进行截止的性质,有时它会给出正值的 4 倍,但有时它会给出更多,具体取决于随机值如何摆脱。我发布了一个“Semi:update”,其中包含我开始工作的代码。继续并更改您的答案或修改您的答案以获得答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-29
  • 1970-01-01
  • 2021-01-19
  • 2014-06-22
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多