[英]How to obtain all possible sub-samples of size n from a dataframe of size N in R?
我有一個包含20個教室[1到20]索引的數據框和每個班級20個不同數量的學生,如何獲得大小為n = 8的所有子樣本並存儲它們,因為我想稍后使用它們進行計算。 我使用了combn()
但只需要一個向量,我可以將它與數據幀一起使用嗎? (抱歉,但我是R的新手),數據框如下:
classrooms students 1 1 29 2 2 30 3 3 35 4 4 28 5 5 32 6 6 20 7 7 25 8 8 22 9 9 32 10 10 26 11 11 27 12 12 34 13 13 27 14 14 28 15 15 33 16 16 21 17 17 36 18 18 24 19 19 19 20 20 32
它就像將函數傳遞給combn
一樣簡單。 simplify = FALSE
表示將返回一個列表。
假設您想要數據集教室中8個教室的所有可能組合
combinations <- combn(nrow(classrooms), 8, function(x,data) data[x,],
simplify = FALSE, data =classrooms )
head(combinations, n = 2)
[[1]]
classrooms students
1 1 29
2 2 30
3 3 35
4 4 28
5 5 32
6 6 20
7 7 25
8 8 22
[[2]]
classrooms students
1 1 29
2 2 30
3 3 35
4 4 28
5 5 32
6 6 20
7 7 25
9 9 32
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.