Skip to content
Prev 154777 / 398503 Next

give all combinations

Yuan Jian, sending 9 emails within the span of few seconds all with 
similar text is very confusing to say the least!

Carl, look up combinations() and permutations() in the gtools package.


For two case scenario, you can use combinations()

    v <- c("a","b","c")

    library(gtools)
    tmp <- combinations(3, 2, v,repeats=TRUE)
    apply( tmp, 1, paste, collapse="" )
    [1] "aa" "ab" "ac" "bb" "bc" "cc"


For more than two cases, I don't know of an elegant way except to 
generate all possible permutations and then eliminate those with the 
same ingredients. This function will be slow for large numbers!


    multiple.combinations <- function( vec, times ){

       input <- vector( mode="list", times )
       for(i in 1:times) input[[i]] <- vec

       out <- expand.grid( input )
       out <- apply( out, 1, function(x) paste( sort(x), collapse="" ) )
       unique.out <- unique(out)
       return(unique.out)
    }

   multiple.combinations( v, 3 )
   [1] "aaa" "aab" "aac" "abb" "abc" "acc" "bbb" "bbc" "bcc" "ccc"

   multiple.combinations( v, 6 )
   "aaaaaa" "aaaaab" "aaaaac" "aaaabb" "aaaabc" "aaaacc" "aaabbb"
   "aaabbc" "aaabcc" "aaaccc" "aabbbb" "aabbbc" "aabbcc" "aabccc"
   "aacccc" "abbbbb" "abbbbc" "abbbcc" "abbccc" "abcccc" "accccc"
   "bbbbbb" "bbbbbc" "bbbbcc" "bbbccc" "bbcccc" "bccccc" "cccccc"

Regards, Adai
Carl Witthoft wrote: