How to get a set of all Combination in R with given conditions?

Viewed 83

I have a set:

lynx <- c(1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,4,4,4,5,5,6,7,8,9)

I want to return a set of all combinations with repetitions allowed from the above set, for example:

1 1 1 1 1
1 2 2 8 9

I used the combination function from library gtools but it doesn't help

I tried:

combination(n = 9, r = 5, v =  lynx, repeats.allowed=TRUE)

which returned

        [,1] [,2] [,3] [,4] [,5]
    [1,]    1    1    1    1    1
    [2,]    1    1    1    1    2
    [3,]    1    1    1    1    3
    [4,]    1    1    1    1    4

But the issue is that it also returns,

  [152,]    1    1    2    8    8

which I don't want since there are no two 8s in the set.

2 Answers

One way is to create a matching vector lyncidx <- 1:length(lynx) , do standard combination or permutation on that set, and then use the results to index into lynx .
lyncidx contains all distinguishable items, so standard set theory tools work fine. Then, e.g., for an output of foo = 1,7,12,20 you would grab the values of lynx[foo] to get

1,1,1,2 as desired

Thanks @ekoam

lynx <- c(1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,4,4,4,5,5,6,7,8,9)

comb <- combinations(freq = table(lynx), k = 5, x = unique(lynx))

comb

library: arrangements

Related