R - Permutations between 2 or more vectors, with constraints -
i generate possible permutations between 2 or more vectors, but;
- order important.
- the first number must lesser second, , second must lesser third.
- there cannot same number.
for instance:
a <- c(3, 5, 8) b <- c(8, 10, 12) c <- c(12, 15, 20)
the first element a
, second b
, third c
.
possible results be:
(3, 8, 12), (3, 8, 15), (3, 8, 20), (3, 10, 12), (3, 10, 15) , (3, 10, 20).
but there shouldn't results repeated numbers, instance:
(8, 8, 12), (8, 12, 12).
how can accomplished using r?
if understand rules correctly, should work.
a <- c(3, 5, 8) b <- c(8, 10, 12) c <- c(12, 15, 20) f <- function(x,y) lapply(y[y>tail(x,1)], function(zz) c(x,zz)) g <- function(x,y) unlist(lapply(x,f,y=y), recursive=false) do.call(rbind,g(g(a,b),c)) # [,1] [,2] [,3] # [1,] 3 8 12 # [2,] 3 8 15 # [3,] 3 8 20 # [4,] 3 10 12 # [5,] 3 10 15 # [6,] 3 10 20 # [7,] 3 12 15 # [8,] 3 12 20 # [9,] 5 8 12 # [10,] 5 8 15 # [11,] 5 8 20 # [12,] 5 10 12 # [13,] 5 10 15 # [14,] 5 10 20 # [15,] 5 12 15 # [16,] 5 12 20 # [17,] 8 10 12 # [18,] 8 10 15 # [19,] 8 10 20 # [20,] 8 12 15 # [21,] 8 12 20
for 4 vectors, use
do.call(rbind,g(g(g(a,b),c),d))
and on.
Comments
Post a Comment