Yesterday a member of COS asked how to generate all the elements of {all sets consisting of arbitrary combinations of n elements} in R and I didn’t know the function combn() then, so after a while I constructed a simple loop to fulfill this function (later I found this was wrong because it didn’t enumerate all possible combinations!):
> x = 1:5 # as an example, you may change this vector
> n = length(x)
> for (i in 1:n) {
if (i == 1) {
for (j in 1:n) {
print(x[j])
}
}
else {
for (j in 1:(n - i + 1)) {
for (k in (j + i - 1):n) {
print(c(x[j:(j + i - 2)], x[k]))
}
}
}
}
The output is:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 1 2
[1] 1 3
[1] 1 4
[1] 1 5
[1] 2 3
[1] 2 4
[1] 2 5
[1] 3 4
[1] 3 5
[1] 4 5
[1] 1 2 3
[1] 1 2 4
[1] 1 2 5
[1] 2 3 4
[1] 2 3 5
[1] 3 4 5
[1] 1 2 3 4
[1] 1 2 3 5
[1] 2 3 4 5
[1] 1 2 3 4 5
Just now when I was reading the help text of the function choose(), I found that there had already been a function combn() in the package utils, which is very appropriate for this situation. For example:
> combn(x = 5, m = 3)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 1 1 1 1 1 2 2 2 3
[2,] 2 2 2 3 3 4 3 3 4 4
[3,] 3 4 5 4 5 5 4 5 5 5
So the problem in the beginning will be much easier.
赞赏
作为一名没有固定工作的自由职业者,我非常感谢您通过捐赠的方式来支持我的写作和开源软件开发。当然,捐赠纯属自愿。无论金额多少,都是一片诚挚的心意。支付方式如下:
| 微信 | ← 奋力支开它俩 → | 支付宝 |
|---|---|---|
![]() |
其它爱心通道 ↓ Venmo: @yihui_xie Zelle: xie@yihui.name PayPal: xie@yihui.name |
![]() |
若使用 Venmo/Zelle/Paypal,请添加备注“gift”或“donation”,以免捐赠被视为我的可税收入。若使用 Paypal,支付类型请选 Family and Friends,而不要选 Goods and Services。
在不影响生活的前提下,我会将收到的捐赠以尽量大的比例回馈给开源社区和慈善机构。作为参考,2024-25 年间我共收到约三万美元捐赠,完税后我转手捐出了一万五千美元。

