Enumeration of all subsets of a vector for a given size

The function choose(n,k)indicates how many subsets of size kexist for a set of elements n. Suppose I need to actually list these subsets, how do I create them? In other words, I am looking for a function that takes a vector x(lengths n) and a number kand returns a list of vectors, each of which has a size k, with subsets x, the length of the list should, of course, be choose(length(x),k). eg

enum.choose = function(x,k) {
    # implementation should go here
{

enum.choose(1:3,2)

# should be:
# [[1]]
#    1  2
# [[2]]
#    1  3
# [[3]]
#    2  3
+4
source share
1 answer

EDIT


, combn(1:3, 2, simplify = FALSE) , . @Ramnath , .

> combn(1:3, 2, simplify = FALSE)
## [[1]]
## [1] 1 2

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

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

, *apply .



@Ramnath, :

enum.choose <- function(x, k) {
  if(k > length(x)) stop('k > length(x)')
  if(choose(length(x), k)==1){
    list(as.vector(combn(x, k)))
  } else {
    cbn <- combn(x, k)
    lapply(seq(ncol(cbn)), function(i) cbn[,i])
  }
}

:

> enum.choose(1:3, 2)
# [[1]]
# [1] 1 2
# 
# [[2]]
# [1] 1 3
# 
# [[3]]
# [1] 2 3
> enum.choose(c(1, 2, 5, 4), 3)
# [[1]]
# [1] 1 2 5
# 
# [[2]]
# [1] 1 2 4
# 
# [[3]]
# [1] 1 5 4
# 
# [[4]]
# [1] 2 5 4
> enum.choose(1:4, 4)
# [[1]]
# [1] 1 2 3 4
> enum.choose(1:5, 6)
# Error in enum.choose(1:5, 6) : k > length(x)
+5

Source: https://habr.com/ru/post/1540065/


All Articles