【发布时间】:2021-09-22 03:23:11
【问题描述】:
我有一个包含两个分组变量和一个结果变量的数据集。我正在尝试从该数据集中模拟采样,但我只想要 either 变量中没有 ID 重复的样本。
我的数据结构如下,但有几百行:
structure(list(wteam = c("a", "a", "b", "c", "c", "d" ), week = c(1, 1, 1, 2, 2, 2), dif = c(0.649077088, 0.089812768, 0.173061282, 0.362544332, 0.459545808, 0.331745704)), row.names = c(NA, 6L), class = "data.frame")
我正在尝试从数据集中抽取 23 个观察值,这样 wteam 和 week 都不能在样本中重复。
我目前的方法效率极低:
sims<-10
weeks<-23
outs<-as.data.frame(matrix(0,ncol = sims, nrow = weeks))
start<-as.data.frame(matrix(0,ncol = 3, nrow = 23))
names(start)<-names(nfl_cur)
for(i in 1:sims) {
start[1,]<- nfl_cur %>% sample_n(1)
nfl_cur2 <- subset(nfl_cur, !(wteam %in% start$wteam))
nfl_cur2 <- subset(nfl_cur, !(week %in% start$week))
start[2,]<-nfl_cur2 %>% sample_n(1)
nfl_cur3 <- subset(nfl_cur2, !(wteam %in% start$wteam))
nfl_cur3 <- subset(nfl_cur2, !(week %in% start$week))
start[3,]<-nfl_cur3 %>% sample_n(1)
nfl_cur4 <- subset(nfl_cur3, !(wteam %in% start$wteam))
nfl_cur4 <- subset(nfl_cur3, !(week %in% start$week))
...
outs[,i]<-start$dif
}
然后我重复直到我到达 23。但是,当我运行代码时,在第一次迭代之后,“out”数据帧被填充为 0,我假设因为 nfl_cur 仍在从开始过滤。
任何帮助将不胜感激!
【问题讨论】:
标签: r unique simulation sampling