如何使用tidyr::crossing函数

How to use tidyr::crossing function

有一个函数叫做tidyr::crossing

根据帮助功能,它是这样做的:‘crossing()’ is a wrapper around ‘expand_grid()’ that de-duplicates and sorts its inputs

然而,当我尝试比较 expand.grid()crossing() 时,我没有看到它们正在退出相似的值:

> 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]>   

你能帮我理解一下 crossing() 函数到底是做什么的吗?在帮助页面中,似乎没有示例

如果你使用向量而不是列表,你就会明白为什么它们几乎相同但有额外的排序和重复数据删除:

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

reprex package (v2.0.1)

于 2021-09-30 创建

expand_gridexpand.grid 和 returns 的 tidyverse 版本 tibble 而不是 data.frame.