简体   繁体   中英

Finding permutation of objects from several vectors with different length using r

I have about eight different vectors containing names:

Vector named "first" has names like this:

     [1] "Brandon Belt"    "Conor Gillaspie" "Buster Posey"  

Vector named "second" has names like this:

     [1] "Starlin Castro"  "Kelby Tomlinson" "Chris Coghlan" 

My concern here is to perform permutation on all eight vectors to get all possible permutations, like this:

   Trevor Brown Brandon Belt Starlin Castro Chris Coghlan Brandon Crawford Gregor Blanco Denard Span Gregor Blanco

   Trevor Brown Brandon Belt Starlin Castro Chris Coghlan Brandon Crawford Gregor Blanco Denard Span Angel Pagan
   .
   .
   .
   Buster Posey Buster Posey Chris Coghlan Kelby Tomlinson Kelby Tomlinson Kelby Tomlinson Angel Pagan Kelby Tomlinson

Several vectors can share same names in it, which is why list above has duplicate names.

I had such a hard time with permutation work with this because:

1) I couldn't find a way to perform permutation on vectors with different lengths.

2) I tried using for loop for each vector, but that is very time-consuming.

Please advise me on finding efficient programming to come up with all permutations.

Here are lengths of all eight vectors: 6,3,3,5,7,3,3,2

So this will give 34020 possibilities. Please find solutions that can help me deal with permutations that would result in 10000000+ possibilities.

This expands on HubertL's comment. The native data structure in R for vectors of different lengths is the list. Here is an example that uses numeric vectors instead of character vectors:

expand.grid(list(1:6, 1:3, 1:3))

Will create permutations of three vectors of size 6, 3, 3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM