2 回答

TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超3個(gè)贊
我建議使用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)
對(duì)于stratified,您基本上指定數(shù)據(jù)集,分層列和表示每個(gè)組所需大小的整數(shù)或表示要返回的分?jǐn)?shù)的小數(shù)(例如,.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
對(duì)于sample_n首先要?jiǎng)?chuàng)建一個(gè)分組表(使用group_by),然后指定想要觀測(cè)次數(shù)。如果你想要比例取樣,你應(yīng)該使用sample_frac。
library(dplyr)
set.seed(1)
out2 <- d %>%
group_by(age, lc) %>%
sample_n(30)
# table(out2$age, out2$lc)

TA貢獻(xiàn)1807條經(jīng)驗(yàn) 獲得超9個(gè)贊
我建議使用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)
對(duì)于stratified,您基本上指定數(shù)據(jù)集,分層列和表示每個(gè)組所需大小的整數(shù)或表示要返回的分?jǐn)?shù)的小數(shù)(例如,.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
對(duì)于sample_n首先要?jiǎng)?chuàng)建一個(gè)分組表(使用group_by),然后指定想要觀測(cè)次數(shù)。如果你想要比例取樣,你應(yīng)該使用sample_frac。
library(dplyr)
set.seed(1)
out2 <- d %>%
group_by(age, lc) %>%
sample_n(30)
# table(out2$age, out2$lc)
- 2 回答
- 0 關(guān)注
- 643 瀏覽
添加回答
舉報(bào)