【问题标题】:Efficient way to sample per group with given number/proportions in R在R中使用给定数量/比例对每组进行采样的有效方法
【发布时间】:2020-12-02 13:49:44
【问题描述】:

我想知道是否有一种有效的组抽样方法,选择一个整数和/或比例从它们中抽样。我知道sample_n 的存在,并且它适用于分组的dfs,但据我所知,它为每个组采样相同的数字。

在一个简单的情况下,对问题的最小描述是从数据帧mpg 中采样 5 个随机行(或这些行的索引向量)用于cyl == 4,7 用于cyl == 6 和3 代表cyl == 8

【问题讨论】:

    标签: r random group-by


    【解决方案1】:

    试试sampling::strat() 功能。 size 参数是一个计数向量。文档说

    "size = 层样本大小的向量(按层的顺序排列) 在输入数据集中给出)。”

    library(sampling)
    
    # filter to the groups of interest
    dat <- mpg[mpg$cyl %in% c(4, 6, 8),]
    
    # vector of counts for each group (in the order those groups appear in the data)
    strata <- strata(data = dat, stratanames="cyl", size = c(5,7,3) , method = "srswor")
    
    # use the 'ID_unit' vector to subset the original data
    dat[strata$ID_unit,]
    

    【讨论】:

      猜你喜欢
      • 2017-04-16
      • 2013-10-19
      • 1970-01-01
      • 2013-02-23
      • 2013-03-08
      • 2020-02-12
      • 1970-01-01
      • 2017-03-03
      相关资源
      最近更新 更多