[R] Concatenating elements from lists via combinations

Alrik Thiem alrik.thiem at gmail.com
Fri Mar 6 11:07:11 CET 2015


Dear R-help list,

I have a problem in which I would like to concatenate elements from lists in
a combinational order. For example, I have a list of n character vectors
(here 3), each with m elements (here 7,3,1):

lst <- list(c("a","aB","aBC","aC","B","BC","C"), c("B","Bc","c"), c("D"))

[[1]]
[1] "a"   "aB"  "aBC" "aC"  "B"   "BC"  "C"  
[[2]]
[1] "B"  "Bc" "c" 
[[3]]
[1] "D"

As the first list element has seven, the second has three and the third has
one element, there are 21 different combinations of the individual vector
elements: 

idx <- expand.grid(1:7,1:3,1:1)

   Var1 Var2 Var3
1     1    1    1
2     2    1    1
.     .    .    .
6     6    1    1
7     7    1    1
8     1    2    1
9     2    2    1
.     .    .    .
20    6    3    1
21    7    3    1

How could I create an exhaustive list of length 21 now, each of whose
elements contains a unique combination of vector elements? I.e., the final
list should look like this

[[1]]
[1] "a" "B" "D"  
[[2]]
[1] "aB" "B" "D" 
[[3]]
[1] "aBC" "B" "D"
[[4]]
[1] "aC" "B" "D"
.....
[[21]]
[1] "C" "c" "D"

Many thanks for help,
Alrik


********************************
Alrik Thiem
Post-Doctoral Researcher

Department of Philosophy
University of Geneva
Rue de Candolle 2
CH-1211 Geneva

+41 76 527 80 83

http://www.alrik-thiem.net
http://www.compasss.org



More information about the R-help mailing list