【问题标题】:Stratified sampling on factor因子分层抽样
【发布时间】:2015-05-07 09:44:20
【问题描述】:

我有一个包含 1000 行的数据集,其结构如下:

     device geslacht leeftijd type1 type2
1       mob        0       53     C     3
2       tab        1       64     G     7
3        pc        1       50     G     7
4       tab        0       75     C     3
5       mob        1       54     G     7
6        pc        1       58     H     8
7        pc        1       57     A     1
8        pc        0       68     E     5
9        pc        0       66     G     7
10      mob        0       45     C     3
11      tab        1       77     E     5
12      mob        1       16     A     1

我想做一个 80 行的样本,由 type1 = A 的 10 行、type1 = B 的 10 行等组成。有没有人可以帮助他?

【问题讨论】:

    标签: r dataframe sampling


    【解决方案1】:

    以下是我使用data.table 处理此问题的方法

    library(data.table)
    indx <- setDT(df)[, .I[sample(.N, 10, replace = TRUE)], by = type1]$V1
    df[indx]
    #     device geslacht leeftijd type1 type2
    #  1:    mob        0       45     C     3
    #  2:    mob        0       53     C     3
    #  3:    tab        0       75     C     3
    #  4:    mob        0       53     C     3
    #  5:    tab        0       75     C     3
    #  6:    mob        0       45     C     3
    #  7:    tab        0       75     C     3
    #  8:    mob        0       53     C     3
    #  9:    mob        0       53     C     3
    # 10:    mob        0       53     C     3
    # 11:    mob        1       54     G     7
    #...
    

    或者更简单的版本是

    setDT(df)[, .SD[sample(.N, 10, replace = TRUE)], by = type1]
    

    基本上,我们从type1 的每组中的行索引中进行抽样(替换 - 因为每组中的行少于 10 行),然后按此索引对数据进行子集


    dplyr 类似,您可以这样做

    library(dplyr)
    df %>% 
      group_by(type1) %>%
      sample_n(10, replace = TRUE)
    

    【讨论】:

      【解决方案2】:

      基础 R 解决方案:

      do.call(rbind,
              lapply(split(df, df$type1), function(i)
                i[sample(1:nrow(i), size = 10, replace = TRUE),]))
      

      编辑:

      @BrodieG 建议的其他解决方案

      with(DF, DF[unlist(lapply(split(seq(type), type), sample, 10, TRUE)), ])
      
      with(DF, DF[c(sapply(split(seq(type), type), sample, 10, TRUE)), ])
      

      【讨论】:

        【解决方案3】:

        基础 R 中的另一个选项:

        df[as.vector(sapply(unique(df$type1), 
                            function(x){
                                sample(which(df$type1==x), 10, replace=T)
                            })), ]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-10-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-10-22
          • 2017-10-31
          • 1970-01-01
          相关资源
          最近更新 更多