假设 df 是您的数据框,default 是指示谁默认的列。
无需更换即可取样:
df[c(sample(which(df$default),30), sample(which(!df$default),70)),]
使用替换进行采样(即可能重复记录):
df[c(sample(which(df$default),30,TRUE), sample(which(!df$default),70,TRUE)),]
或者,如果您不想指定违约者和非违约者的确切数量,您可以为每行指定一个抽样概率:
set.seed(1)
df <- data.frame(default=rbinom(250,1,.5), y=rnorm(250))
n <- 100 # could be any number, but closer you get to nrow(df) the less the weights matters
s <- sample(seq_along(df$default), n, prob=ifelse(df$default, .3, .7))
table(df$default[s])
#
# 0 1
# 61 39
n <- 150 # could be any number, but closer you get to nrow(df) the less the weights matters
s <- sample(seq_along(df$default), n, prob=ifelse(df$default, .3, .7))
table(df$default[s])
#
# 0 1
# 97 53