Question

I have a problem I think best can be solved using cominatorics.

Lets say you have values 4 values (2,5,6,7). I would like to get all vectors where I pick out 3 of them, that is I would like a matrix with (2,5,6),(2,5,7),(5,6,7). I would like to do this with a general vector. How do I do it?

Was it helpful?

Solution

x <- c(2, 5, 6, 7)
combn(x, 3)

gives

> combn(x, 3)
     [,1] [,2] [,3] [,4]
[1,]    2    2    2    5
[2,]    5    5    6    6
[3,]    6    7    7    7

OTHER TIPS

I have created a package iterpc which is able to solve most of the combination/permutation related problems.

library(iterpc)
x <- c(2, 5, 6, 7)
# combinations
getall(iterpc(4, 3, label=x))
# combinations with replacement
getall(iterpc(4, 3, replace=TRUE, label=x))
# permutations
getall(iterpc(4, 3, label=x, ordered=TRUE))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top