Combinations of multiple vectors in R

后端 未结 2 1731
無奈伤痛
無奈伤痛 2020-12-03 15:45

I\'m not sure if permutations is the correct word for this. I want to given a set of n vectors (i.e. [1,2],[3,4] and [2,3]) permute th

相关标签:
2条回答
  • 2020-12-03 16:07

    This is a useful case for storing the vectors in a list and using do.call() to arrange for an appropriate function call for you. expand.grid() is the standard function you want. But so you don't have to type out or name individual vectors, try:

    > l <- list(a = 1:2, b = 3:4, c = 2:3)
    > do.call(expand.grid, l)
      a b c
    1 1 3 2
    2 2 3 2
    3 1 4 2
    4 2 4 2
    5 1 3 3
    6 2 3 3
    7 1 4 3
    8 2 4 3
    

    However, for all my cleverness, it turns out that expand.grid() accepts a list:

    > expand.grid(l)
      a b c
    1 1 3 2
    2 2 3 2
    3 1 4 2
    4 2 4 2
    5 1 3 3
    6 2 3 3
    7 1 4 3
    8 2 4 3
    
    0 讨论(0)
  • 2020-12-03 16:29

    This is what expand.grid does.

    Quoting from the help page: Create a data frame from all combinations of the supplied vectors or factors. The result is a data.frame with a row for each combination.

    expand.grid(
        c(1, 2),
        c(3, 4),
        c(2, 3)
    )
    
      Var1 Var2 Var3
    1    1    3    2
    2    2    3    2
    3    1    4    2
    4    2    4    2
    5    1    3    3
    6    2    3    3
    7    1    4    3
    8    2    4    3
    
    0 讨论(0)
提交回复
热议问题