通过以下示例数据框,我想从因子“群组”的每个级别绘制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。任何援助将不胜感激。
答案 0 :(得分:8)
以这种方式:
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
答案 1 :(得分:5)
为什么不
library(dplyr)
data %>%
select(ID, Cohort) %>%
distinct %>%
group_by(Cohort) %>%
sample_frac(0.4) %>%
left_join(data)