【问题标题】:R simulating sample with unique observationsR模拟具有独特观察的样本
【发布时间】: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


    【解决方案1】:

    如果我理解了,这可能会对你有所帮助

    #Libraries
    
    library(dplyr)
    
    #Example Data
    df <-
      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")
    
    #Sample 1 by each wteam + week
    
    df %>% 
      group_by(wteam,week) %>% 
      sample_n(1)
    
    # A tibble: 4 x 3
    # Groups:   wteam, week [4]
      wteam  week    dif
      <chr> <dbl>  <dbl>
    1 a         1 0.0898
    2 b         1 0.173 
    3 c         2 0.363 
    4 d         2 0.332 
    

    【讨论】:

    • 嗨,Vincius,感谢您的回答!我之前曾尝试过,但每个样本中都会重复“周”的级别。你知道有一种抽样方法可以防止“week”和“wteam”这两个级别的重复吗?
    【解决方案2】:

    data.table 的选项

    library(data.table)
    setDT(df)[, .SD[sample(seq_len(.N), 1)], .(wteam, week)]
    

    -输出

    wteam week        dif
    1:     a    1 0.08981277
    2:     b    1 0.17306128
    3:     c    2 0.36254433
    4:     d    2 0.33174570
    

    【讨论】:

    • 嘿阿克伦,我很欣赏这个答案。当我运行这段代码时,我仍然在“week”变量中得到重复。您是否知道一种采样方式,因此“week”和“wteam”都不能在每个样本中重复?
    猜你喜欢
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 2012-07-09
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多