首页 > 解决方案 > 在R中使用给定数量/比例对每组进行采样的有效方法

问题描述

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

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

标签: rrandomgroup-by

解决方案


试试这个sampling::strat()功能。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,]

推荐阅读