Search code examples
rlistmatrixcombinationssymmetric

R - Combinations of a list WITH duplicates?


How can I get all the combinations of a list with duplicates. By duplicates I mean an element with itself. I am building a symmetric matrix.

names.list<-c("A","B","C")
as.data.frame(t(combn(names.list,2)))

Result is:

   V1  V2
1   A   B
2   A   C
3   B   C

When I want:

   V1  V2
1   A   A
2   A   B
3   A   C
4   B   B
5   B   C
6   C   C

Or even:

   V1  V2
1   A   A
2   A   B
3   A   C
4   B   A
5   B   B
6   B   C
7   C   A
8   C   B
9   C   C

But my matrices are large so I would like to keep combinations to a minimum (so preferably the second result), since more combinations = more computations = larger run times..

Thanks.


Solution

  • It sounds like you're looking for expand.grid instead of combn:

    expand.grid(names.list, names.list)
    #   Var1 Var2
    # 1    A    A
    # 2    B    A
    # 3    C    A
    # 4    A    B
    # 5    B    B
    # 6    C    B
    # 7    A    C
    # 8    B    C
    # 9    C    C
    

    Update

    There's also combinations from "gtools" which would give you your preferred output.

    library(gtools)
    combinations(3, 2, names.list, repeats = TRUE)
    #     [,1] [,2]
    # [1,] "A"  "A" 
    # [2,] "A"  "B" 
    # [3,] "A"  "C" 
    # [4,] "B"  "B" 
    # [5,] "B"  "C" 
    # [6,] "C"  "C"