[R] Generating permutations that always include one specific element

David Winsemius dwinsemius at comcast.net
Sat Dec 19 14:44:04 CET 2009


On Dec 18, 2009, at 6:27 PM, Raymond Danner wrote:

> Dear R community,
>
> I am trying to create a matrix of permutations of a vector:
> bands <- c("AL", "B", "DB", "DG", "G", "K", "LB", "LG", "MG", "O",  
> "P",
> "PI", "PK", "PU", "R", "V", "W", "Y")
>
> Each permutation must be 4 characters long. permutations() from the  
> gtools
> package does this easy enough:
> possible.combos <- permutations(18, 4, bands)
>
> However, “AL” must be one of the elements in each permutation.
> Any ideas?

Just use the ones that satisfy your requirements:

 > str(possible.combos)
  chr [1:73440, 1:4] "AL" "AL" "AL" "AL" "AL" "AL" "AL" "AL" ...
 > str(apply(possible.combos, 1, function(x) "AL" %in% x))
  logi [1:73440] TRUE TRUE TRUE TRUE TRUE TRUE ...
 > sum(apply(possible.combos, 1, function(x) "AL" %in% x))
[1] 16320

And you will need to clarify what you mean by must be "4 characters  
long" because none of the strings that would be formed with the method  
you describe would qualify unless you really mean "4 elements long".

-- 

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list