【问题标题】:R: Stratified random sample proportion of unique ID's by grouping variableR:通过对变量进行分组的唯一 ID 的分层随机样本比例
【发布时间】:2016-02-23 14:52:06
【问题描述】:

使用以下示例数据框,我想从因子“队列”的每个级别中抽取 ID 的“ID”的分层随机样本(例如 40%):

data<-structure(list(Cohort = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), ID = structure(1:20, .Label = c("a1 ", 
"a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "b10", "b11", 
"b12", "b13", "b14", "b15", "b16", "b17", "b18", "b19", "b20"
), class = "factor")), .Names = c("Cohort", "ID"), class = "data.frame", row.names = c(NA, 
-20L))

我只知道如何使用以下方法绘制随机数量的行:

library(dplyr)
data %>% 
group_by(Cohort) %>%
sample_n(size = 10)

但我的实际数据是纵向的,所以我在每个群组中有多个相同 ID 的案例和几个不同大小的群组,因此需要选择一定比例的唯一 ID。任何援助将不胜感激。

【问题讨论】:

  • 您应该提供重现您遇到的问题的数据,否则我们无法理解......所以如果您有多个ID,请使用此功能制作数据;)

标签: r random dplyr sampling


【解决方案1】:

这是一种方法:

data %>% group_by(Cohort) %>%
  filter(ID %in% sample(unique(ID), ceiling(0.4*length(unique(ID)))))

这将返回包含随机抽样 ID 的所有行。换句话说,我假设您有与每一行相关的测量值,并且您想要每个采样 ID 的所有测量值。 (如果您只想为每个采样的 ID 返回一行,那么@bramtayl 的答案将做到这一点。)

例如:

data = data.frame(rbind(data, data), value=rnorm(2*nrow(data)))

data %>% group_by(Cohort) %>%
  filter(ID %in% sample(unique(ID), ceiling(0.4*length(unique(ID)))))

   Cohort     ID       value
    (int) (fctr)       (dbl)
1       1    a1  -0.92370760
2       1     a2 -0.37230655
3       1     a3 -1.27037502
4       1     a7 -0.34545295
5       2    b14 -2.08205561
6       2    b17  0.31393998
7       2    b18 -0.02250819
8       2    b19  0.53065857
9       2    b20  0.03924414
10      1    a1  -0.08275011
11      1     a2 -0.10036822
12      1     a3  1.42397042
13      1     a7 -0.35203237
14      2    b14  0.30422865
15      2    b17 -1.82008014
16      2    b18  1.67548568
17      2    b19  0.74324596
18      2    b20  0.27725794

【讨论】:

    【解决方案2】:

    为什么不

    library(dplyr)
    
    data %>%
      select(ID, Cohort) %>%
      distinct %>%
      group_by(Cohort) %>%
      sample_frac(0.4) %>%
      left_join(data)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      相关资源
      最近更新 更多