我建议使用stratified
从我的“splitstackshape”包中,或者sample_n
来自“dplyr”包:
## Sample data
set.seed(1)
n <- 1e4
d <- data.table(age = sample(1:5, n, T),
lc = rbinom(n, 1 , .5),
ants = rbinom(n, 1, .7))
# table(d$age, d$lc)
For stratified
,您基本上指定数据集、分层列以及表示您想要从每个组中获得的大小的整数或表示您想要返回的分数的小数(例如,0.1 表示每个组中的 10%)。
library(splitstackshape)
set.seed(1)
out <- stratified(d, c("age", "lc"), 30)
head(out)
# age lc ants
# 1: 1 0 1
# 2: 1 0 0
# 3: 1 0 1
# 4: 1 0 1
# 5: 1 0 0
# 6: 1 0 1
table(out$age, out$lc)
#
# 0 1
# 1 30 30
# 2 30 30
# 3 30 30
# 4 30 30
# 5 30 30
For sample_n
您首先创建一个分组表(使用group_by
),然后指定您想要的观测值数量。如果您想要比例采样,则应该使用sample_frac
.
library(dplyr)
set.seed(1)
out2 <- d %>%
group_by(age, lc) %>%
sample_n(30)
# table(out2$age, out2$lc)