r - 在R中使用给定数量/比例对每组进行采样的有效方法
问题描述
我想知道是否有一种有效的对组进行抽样的方法,选择一个整数和/或比例从它们中抽样。我知道存在sample_n
分组 dfs 并且它适用于分组 dfs,但据我所知,它对每个组采样相同的数字。
在一个简单的情况下,对问题的最小描述是从数据帧mpg
中抽取 5 个随机行(或这些行的索引向量)cyl == 4
,7 个cyl == 6
和 3 个cyl == 8
。
解决方案
试试这个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,]
推荐阅读
- c++ - C++ 模板函数,在其实例化点之前精确计算所有模板类特化
- php - Laravel 雄辩的 JSON 搜索
- html - 如何防止网格 div 的高度随其内容扩展?
- python - Python 函数,最大值为 1.2
- node.js - 类型错误 [ERR_UNKNOWN_FILE_EXTENSION]:
- javascript - 覆盖 Angular 本地特定时间格式
- c++ - 如果一个浮点数在我的机器上是可表示的,它的倒数在我的机器上是否可以表示?
- python - 使用 HuggingFace 微调 ALBERT 问答
- python - 如何在 Heroku 上处理图像
- node.js - 使用网页中的量角器按 id 选择所有元素