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

后端 未结 5 1679
面向向阳花
面向向阳花 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:31

    Since version 1.0.0, tidyr offers its own version of expand.grid(). It completes the existing family of expand(), nesting(), and crossing() with a low-level function that works with vectors.

    When compared to base::expand.grid():

    Varies the first element fastest. Never converts strings to factors. Does not add any additional attributes. Returns a tibble, not a data frame. Can expand any generalised vector, including data frames.

    a <- c("ABC", "DEF", "GHI")
    b <- c("2012-05-01", "2012-05-02", "2012-05-03", "2012-05-04", "2012-05-05")
    
    tidyr::expand_grid(a, b)
    
       a     b         
             
     1 ABC   2012-05-01
     2 ABC   2012-05-02
     3 ABC   2012-05-03
     4 ABC   2012-05-04
     5 ABC   2012-05-05
     6 DEF   2012-05-01
     7 DEF   2012-05-02
     8 DEF   2012-05-03
     9 DEF   2012-05-04
    10 DEF   2012-05-05
    11 GHI   2012-05-01
    12 GHI   2012-05-02
    13 GHI   2012-05-03
    14 GHI   2012-05-04
    15 GHI   2012-05-05
    

提交回复
热议问题