所有大小的所有组合? [英] All combinations of all sizes?

查看:62
本文介绍了所有大小的所有组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我搜索 R中的向量组合时,在SO上有成千上万的结果,但找不到我的问题的答案。抱歉,如果它是重复项:

There are thousands of results on SO when I search for "vector combinations in R" but I can't find the answer to my question. Apologies if it is a duplicate:

我有一个向量(1,2,3,4)并且我想要找到所有组合(n选择2)至(n选择n)。换句话说,对于这个向量,我想要:

I have a vector (1,2,3,4) and I want to find all combinations (n choose 2) to (n choose n). In other words, for this vector I would want:

1,2,3,4
1,2,3
1,2,4
1,3,4
2,3,4
1,2
1,3
1,4
2,3
2,4
3,4

希望代码可以通用,以便一旦我有了一个更大的向量,它就可以通用。

And hopefully the code would be generalizable so that once I have a larger vector, it would be able to generalize.

谢谢!

推荐答案

如果您喜欢紧凑代码

Map(combn, list(x), seq_along(x))
## [[1]]
##      [,1] [,2] [,3] [,4]
## [1,]    1    2    3    4

## [[2]]
##      [,1] [,2] [,3] [,4] [,5] [,6]
## [1,]    1    1    1    2    2    3
## [2,]    2    3    4    3    4    4

## [[3]]
##      [,1] [,2] [,3] [,4]
## [1,]    1    1    1    2
## [2,]    2    2    3    3
## [3,]    3    4    4    4

## [[4]]
##      [,1]
## [1,]    1
## [2,]    2
## [3,]    3
## [4,]    4

为避免重复,您必须处理嵌套列表,但可以使用 unlist

To avoid repetition, you'll have to deal with nested list but you can simplify the result using unlist

res <- Map(combn, list(x), seq_along(x), simplify = FALSE)
unlist(res, recursive = FALSE)
## [[1]]
## [1] 1

## [[2]]
## [1] 2

## [[3]]
## [1] 3

## [[4]]
## [1] 4

## [[5]]
## [1] 1 2

## [[6]]
## [1] 1 3

## [[7]]
## [1] 1 4

## [[8]]
## [1] 2 3

## [[9]]
## [1] 2 4

## [[10]]
## [1] 3 4

## [[11]]
## [1] 1 2 3

## [[12]]
## [1] 1 2 4

## [[13]]
## [1] 1 3 4

## [[14]]
## [1] 2 3 4

## [[15]]
## [1] 1 2 3 4

这篇关于所有大小的所有组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆