【问题标题】:For every 3 rows, take a random row from the 3 out into a test data frame. (R)对于每 3 行,从 3 行中随机抽取一行到测试数据框中。 (右)
【发布时间】:2022-08-19 08:03:31
【问题描述】:

我有一个数据框(df)以每 3 行是一个生物一式三份的方式设置。

首先,对于每3行,我想从3行中随机选择1行,将其从df中取出并放入df_test。

    标签: r


    【解决方案1】:
    library(dplyr)
    df_test <- df %>%
      group_by(grp = (row_number()-1) %/% 3) %>%
      slice_sample(n = 1) %>%
      ungroup()
    

    【讨论】:

      【解决方案2】:

      您应该可以同时sample。如果每个组是n 行的块,则从每个块的开头随机采样0:(n-1) 的偏移量,并将其添加到每个块的开头 - seq(1, nrow(df), n)

      n <- 3
      s <- seq(1, nrow(df), n)
      df[sample(0:(n-1), length(s)) + s,]
      

      尝试运行 1000 次,所选行的分布看起来非常均匀:

      set.seed(1)
      df <- data.frame(matrix(1:18, ncol=2))
      n <- 3
      s <- seq(1, nrow(df), n)
      table(replicate(1000, sample(0:(n-1), length(s)) + s))
      
      #  1   2   3   4   5   6   7   8   9 
      #341 329 330 325 344 331 334 327 339 
      

      【讨论】:

        猜你喜欢
        • 2021-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-03
        • 1970-01-01
        • 2013-04-23
        • 2014-07-12
        • 2010-12-14
        相关资源
        最近更新 更多