Unique combination of all elements from two (or more) vectors

后端 未结 5 1765
面向向阳花
面向向阳花 2020-11-22 03:07

I am trying to create a unique combination of all elements from two vectors of different size in R.

For example, the first vector is

a <- c(\"ABC\         


        
5条回答
  •  情书的邮戳
    2020-11-22 03:18

    you can use order function for sorting any number of columns. for your example

    df <- expand.grid(a,b)
    > df
       Var1       Var2
    1   ABC 2012-05-01
    2   DEF 2012-05-01
    3   GHI 2012-05-01
    4   ABC 2012-05-02
    5   DEF 2012-05-02
    6   GHI 2012-05-02
    7   ABC 2012-05-03
    8   DEF 2012-05-03
    9   GHI 2012-05-03
    10  ABC 2012-05-04
    11  DEF 2012-05-04
    12  GHI 2012-05-04
    13  ABC 2012-05-05
    14  DEF 2012-05-05
    15  GHI 2012-05-05
    
    > df[order( df[,1], df[,2] ),] 
       Var1       Var2
    1   ABC 2012-05-01
    4   ABC 2012-05-02
    7   ABC 2012-05-03
    10  ABC 2012-05-04
    13  ABC 2012-05-05
    2   DEF 2012-05-01
    5   DEF 2012-05-02
    8   DEF 2012-05-03
    11  DEF 2012-05-04
    14  DEF 2012-05-05
    3   GHI 2012-05-01
    6   GHI 2012-05-02
    9   GHI 2012-05-03
    12  GHI 2012-05-04
    15  GHI 2012-05-05`
    

提交回复
热议问题