[R] give all combinations
Adaikalavan Ramasamy
a.ramasamy at imperial.ac.uk
Tue Sep 2 15:31:37 CEST 2008
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:
> I seem to be missing something here:
>
> given a set X:{a,b,c,whatever...}
> the mathematical definition of 'permutation' is the set of all possible
> sequences of the elements of X.
> The definition of 'combination' is all elements of 'permutation' which
> cannot be re-ordered to become a different element.
>
> example: X:{a,b,c}
>
> perm(X) = ab, ab, bc, ba, ca, cb
> comb(X) = ab, ac, bc
>
>
> So maybe a better question for this mailing list is: Are there
> functions available in any R package which produce perm() and comb()
> (perhaps as well as other standard combinatoric functions) ?
>
> Carl
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list