从 data.frame 中抽样,同时控制比例 [分层抽样]

Sampling from a data.frame while controlling for a proportion [stratified sampling]

我有以下数据集

id1<-c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)
status<-c(1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2)
df<-data.frame(id1,status)

df 中,我 40% 的观察 status 是“2”。 我正在寻找一个函数来从 df 中提取 10 个观察样本,同时保持上述比例。

我已经看到了stratified random sampling from data frame in R但是不是讲比例

您可以尝试我的 "splitstackshape" 包中的 stratified 功能:

library(splitstackshape)
stratified(df, "status", 10/nrow(df))
#     id1 status
#  1:   5      1
#  2:  12      1
#  3:   2      1
#  4:   1      1
#  5:   6      1
#  6:   9      1
#  7:  16      2
#  8:  17      2
#  9:  18      2
# 10:  15      2

或者,使用 "dplyr" 中的 sample_frac

library(dplyr)

df %>%
  group_by(status) %>%
  sample_frac(10/nrow(df))

这两个都将采用与原始分组变量成比例的分层样本(因此使用 10/nrow(df),或者等效地,0.5)。