R-Find unique permutations of values

I hope to create all possible permutations of a vector containing two different values, in which I control the proportion of each of the values.

For example, if I have a vector of length three, and I want all possible combinations containing one 1, my desired output is a list that looks like this:

list.1 <- list(c(1,0,0), c(0,1,0), c(0,0,1))

In contrast, if I need all possible combinations containing three 1s, my desired result is a list that looks like this:

list.3 <- list(c(1,1,1))

In other words, the values of the template 1and 0has a value, but it 1should be considered as identical to the rest of 1s.

Based on the search here and elsewhere, I tried several approaches:

expand.grid(0:1, 0:1, 0:1)  # this includes all possible combinations of 1, 2, or 3 ones
permn(c(0,1,1))             # this does not treat the ones as identical (e.g. it produces (0,1,1) twice)
unique(permn(c(0,1,1)))     # this does the job!

, permn combinat . , ( 20, 50% 1 50% 0, :

unique(permn(c(rep(1,10), rep(0, 10))))

# returns the error:
Error in vector("list", gamma(n + 1)) : 
  vector size specified is too large

, , permn , , , R.

- , ?

, - , SO, , , , .

+4
2

dealbreaker, expand.grid . :

combinations <- function(size, choose) {

  d <- do.call("expand.grid", rep(list(0:1), size))
  d[rowSums(d) == choose,]

}

combinations(size=10, choose=3)
#    Var1 Var2 Var3 Var4 Var5 Var6 Var7 Var8 Var9 Var10
# 8     1    1    1    0    0    0    0    0    0     0
# 12    1    1    0    1    0    0    0    0    0     0
# 14    1    0    1    1    0    0    0    0    0     0
# 15    0    1    1    1    0    0    0    0    0     0
# 20    1    1    0    0    1    0    0    0    0     0
# 22    1    0    1    0    1    0    0    0    0     0
...
+1

, (20) (~ 10 ^ 18), . , , . multicool :

library(multicool)

res <- allPerm(initMC(c(rep(0,10),rep(1,10) )))

, .

+1

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


All Articles