Home > Back-end >  Combinations of two lists
Combinations of two lists

Time:06-07

I do have two lists and I want to get all combination of two lists

x <- list(name = c("a", "b", "c"), month = c("D" ,"E", "F", "G"))
y <- list("1" =c(1,2,3),"2"= c(5,6,7,8))

the output should be like

 a  1
 a  2
 a  3
 b  1 
 b  2 
 b  3 
 c  1 
 c  2 
 c  3

 d  5
 d  6
 d  7 
 d  8

... and so on. Basically combination of expand.grid(x[[1]],y[[1]]) and expand.grid(x[[2]],y[[2]])

CodePudding user response:

Simply use Map.

Map(expand.grid, x, y)
# $name
#   Var1 Var2
# 1    a    1
# 2    b    1
# 3    c    1
# 4    a    2
# 5    b    2
# 6    c    2
# 7    a    3
# 8    b    3
# 9    c    3
# 
# $month
#    Var1 Var2
# 1     D    5
# 2     E    5
# 3     F    5
# 4     G    5
# 5     D    6
# 6     E    6
# 7     F    6
# 8     G    6
# 9     D    7
# 10    E    7
# 11    F    7
# 12    G    7
# 13    D    8
# 14    E    8
# 15    F    8
# 16    G    8

You can extend this to get a data frame:

Map(expand.grid, x, y) |>
  c(make.row.names=FALSE) |>
  do.call(what=rbind)
#    Var1 Var2
# 1     a    1
# 2     b    1
# 3     c    1
# 4     a    2
# 5     b    2
# 6     c    2
# 7     a    3
# 8     b    3
# 9     c    3
# 10    D    5
# 11    E    5
# 12    F    5
# 13    G    5
# 14    D    6
# 15    E    6
# 16    F    6
# 17    G    6
# 18    D    7
# 19    E    7
# 20    F    7
# 21    G    7
# 22    D    8
# 23    E    8
# 24    F    8
# 25    G    8

CodePudding user response:

in tidyverse:

Using crossing:

 map2_df(x, y, crossing)

# A tibble: 25 x 2
   `<chr>` `<dbl>`
   <chr>     <dbl>
 1 a             1
 2 a             2
 3 a             3
 4 b             1
 5 b             2
 6 b             3
 7 c             1
 8 c             2
 9 c             3
10 D             5
# ... with 15 more rows

Using nesting:

 nesting(x, y) %>%
    reduce(names(.), ~unnest(.x, all_of(.y)), .init = .)

# A tibble: 25 x 2
   x         y
   <chr> <dbl>
 1 a         1
 2 a         2
 3 a         3
 4 b         1
 5 b         2
 6 b         3
 7 c         1
 8 c         2
 9 c         3
10 D         5
# ... with 15 more rows

CodePudding user response:

Try this

x <- list(name = c("a", "b", "c"), month = c("D" ,"E", "F", "G"))
y <- list("1" =c(1,2,3),"2"= c(5,6,7,8))

ex1 <- expand.grid(x$name , y$`1`)
ex2 <- expand.grid(x$month , y$`2`)
rbind(ex1 , ex2)
#>    Var1 Var2
#> 1     a    1
#> 2     b    1
#> 3     c    1
#> 4     a    2
#> 5     b    2
#> 6     c    2
#> 7     a    3
#> 8     b    3
#> 9     c    3
#> 10    D    5
#> 11    E    5
#> 12    F    5
#> 13    G    5
#> 14    D    6
#> 15    E    6
#> 16    F    6
#> 17    G    6
#> 18    D    7
#> 19    E    7
#> 20    F    7
#> 21    G    7
#> 22    D    8
#> 23    E    8
#> 24    F    8
#> 25    G    8

Created on 2022-06-07 by the reprex package (v2.0.1)

  •  Tags:  
  • r
  • Related