Home > database >  How to use tidyr::crossing function
How to use tidyr::crossing function

Time:10-01

There is a function called tidyr::crossing

As per the help function, it does this: ‘crossing()’ is a wrapper around ‘expand_grid()’ that de-duplicates and sorts its inputs

However when I tried to compare expand.grid() and crossing() I don't see they are retiring similar values:

> expand.grid(list(1:4, 1:4))
   Var1 Var2
1     1    1
2     2    1
3     3    1
4     4    1
5     1    2
6     2    2
7     3    2
8     4    2
9     1    3
10    2    3
11    3    3
12    4    3
13    1    4
14    2    4
15    3    4
16    4    4
> tidyr::crossing(list(1:4, 1:4))
# A tibble: 1 × 1
  `list(1:4, 1:4)`
  <list>          
1 <int [4]>   

Could you please help me to understand what crossing() function exactly does? In there help page, there seem to have no example

CodePudding user response:

If you use vectors instead of lists, you see why they are pretty much the same but with additional sorting and deduplication:

tidyr::crossing(
  a = 1:3,
  b = 1:3
)
#> # A tibble: 9 x 2
#>       a     b
#>   <int> <int>
#> 1     1     1
#> 2     1     2
#> 3     1     3
#> 4     2     1
#> 5     2     2
#> 6     2     3
#> 7     3     1
#> 8     3     2
#> 9     3     3

tidyr::expand_grid(
  a = 1:3,
  b = 1:3
)
#> # A tibble: 9 x 2
#>       a     b
#>   <int> <int>
#> 1     1     1
#> 2     1     2
#> 3     1     3
#> 4     2     1
#> 5     2     2
#> 6     2     3
#> 7     3     1
#> 8     3     2
#> 9     3     3


set.seed(1)
c <- sample(seq(4))
c
#> [1] 1 3 4 2

tidyr::crossing(a = 1:3, c)
#> # A tibble: 12 x 2
#>        a     c
#>    <int> <int>
#>  1     1     1
#>  2     1     2
#>  3     1     3
#>  4     1     4
#>  5     2     1
#>  6     2     2
#>  7     2     3
#>  8     2     4
#>  9     3     1
#> 10     3     2
#> 11     3     3
#> 12     3     4
tidyr::expand_grid(a = 1:3, c)
#> # A tibble: 12 x 2
#>        a     c
#>    <int> <int>
#>  1     1     1
#>  2     1     3
#>  3     1     4
#>  4     1     2
#>  5     2     1
#>  6     2     3
#>  7     2     4
#>  8     2     2
#>  9     3     1
#> 10     3     3
#> 11     3     4
#> 12     3     2

Created on 2021-09-30 by the reprex package (v2.0.1)

expand_grid is the tidyverse verision of expand.grid and returns a tibble instead of a data.frame.

  • Related