R - List All Combinations With combn (Multiple m Values) [duplicate]

情到浓时终转凉″ 提交于 2019-12-24 18:49:24

问题


I would like to build a dataframe that lists all possible combinations of 6 numbers.

I realised that I can use combn(), but with only one value for m. With a bit of playing around I got the desired result by going through step-by-step with the following code -

combi1 <- data.frame(c(1:6))
colnames(combi1) <- 'X1'

combi2 <- data.frame(t(combn(c(1:6), 2)))
combi3 <- data.frame(t(combn(c(1:6), 3)))
combi4 <- data.frame(t(combn(c(1:6), 4)))
combi5 <- data.frame(t(combn(c(1:6), 5)))
combi6 <- data.frame(t(combn(c(1:6), 6)))

Combi <- rbind.fill(combi1, combi2, combi3, combi4, combi5, combi6)

I had to transpose each of the DFs to get them in the right shape.

My problem is that this seems to be quite an in-efficient method. Maybe a bit simplistic. I thought there must surely be some quicker way to code this, but haven't found any solution online that gives me what I'd like.

Possibly build it into a function or a loop somehow? I'm fairly new to R though and haven't had a great deal of practice writing functions.


回答1:


Is it what you want ?

combis <- vector("list", 6)
combi1 <- data.frame(c(1:6))
colnames(combi1) <- 'X1'
combis[[1]] <- combi1
combis[2:6] <- lapply(2:6, function(n) data.frame(t(combn(c(1:6), n))))

do.call(plyr::rbind.fill, combis)

Result:

   X1 X2 X3 X4 X5 X6
1   1 NA NA NA NA NA
2   2 NA NA NA NA NA
3   3 NA NA NA NA NA
4   4 NA NA NA NA NA
5   5 NA NA NA NA NA
6   6 NA NA NA NA NA
7   1  2 NA NA NA NA
8   1  3 NA NA NA NA
9   1  4 NA NA NA NA
10  1  5 NA NA NA NA
11  1  6 NA NA NA NA
12  2  3 NA NA NA NA
13  2  4 NA NA NA NA
14  2  5 NA NA NA NA
15  2  6 NA NA NA NA
16  3  4 NA NA NA NA
17  3  5 NA NA NA NA
18  3  6 NA NA NA NA
19  4  5 NA NA NA NA
20  4  6 NA NA NA NA
21  5  6 NA NA NA NA
22  1  2  3 NA NA NA
23  1  2  4 NA NA NA
24  1  2  5 NA NA NA
25  1  2  6 NA NA NA
26  1  3  4 NA NA NA
27  1  3  5 NA NA NA
28  1  3  6 NA NA NA
29  1  4  5 NA NA NA
30  1  4  6 NA NA NA
31  1  5  6 NA NA NA
32  2  3  4 NA NA NA
33  2  3  5 NA NA NA
34  2  3  6 NA NA NA
35  2  4  5 NA NA NA
36  2  4  6 NA NA NA
37  2  5  6 NA NA NA
38  3  4  5 NA NA NA
39  3  4  6 NA NA NA
40  3  5  6 NA NA NA
41  4  5  6 NA NA NA
42  1  2  3  4 NA NA
43  1  2  3  5 NA NA
44  1  2  3  6 NA NA
45  1  2  4  5 NA NA
46  1  2  4  6 NA NA
47  1  2  5  6 NA NA
48  1  3  4  5 NA NA
49  1  3  4  6 NA NA
50  1  3  5  6 NA NA
51  1  4  5  6 NA NA
52  2  3  4  5 NA NA
53  2  3  4  6 NA NA
54  2  3  5  6 NA NA
55  2  4  5  6 NA NA
56  3  4  5  6 NA NA
57  1  2  3  4  5 NA
58  1  2  3  4  6 NA
59  1  2  3  5  6 NA
60  1  2  4  5  6 NA
61  1  3  4  5  6 NA
62  2  3  4  5  6 NA
63  1  2  3  4  5  6


来源:https://stackoverflow.com/questions/49570793/r-list-all-combinations-with-combn-multiple-m-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!