Reputation: 5
I would like to generate all possible permutations between 2 or more vectors, but;
For instance:
a <- c(3, 5, 8)
b <- c(8, 10, 12)
c <- c(12, 15, 20)
The first element is from a
, the second from b
and the third from c
.
Possible results would be:
(3, 8, 12), (3, 8, 15), (3, 8, 20), (3, 10, 12), (3, 10, 15) and (3, 10, 20).
But there shouldn't be results with repeated numbers, for instance:
(8, 8, 12), (8, 12, 12).
How can this be accomplished using R?
Upvotes: 0
Views: 265
Reputation: 59365
If I understand your rules correctly, this 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, you would use
do.call(rbind,g(g(g(a,b),c),d))
and so on.
Upvotes: 1