2 回答

TA貢獻1830條經驗 獲得超3個贊
我建議使用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)
對于stratified,您基本上指定數據集,分層列和表示每個組所需大小的整數或表示要返回的分數的小數(例如,.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
對于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)

TA貢獻1807條經驗 獲得超9個贊
我建議使用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)
對于stratified,您基本上指定數據集,分層列和表示每個組所需大小的整數或表示要返回的分數的小數(例如,.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
對于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)
- 2 回答
- 0 關注
- 647 瀏覽
添加回答
舉報