tidyr::expand_grid() not behaving as expected; what am I missing?

Viewed 101

Here's my reprex:

library(tidyverse)

# make some data
a = tibble(b=1:2,c=2:1)
print(a)
#> # A tibble: 2 x 2
#>       b     c
#>   <int> <int>
#> 1     1     2
#> 2     2     1

expand_grid(a) # doesn't produce the expected output
#> # A tibble: 2 x 2
#>       b     c
#>   <int> <int>
#> 1     1     2
#> 2     2     1

# expected output achieved by:
(
    a
    %>% as.list()
    %>% map(unique)
    %>% cross_df()
) 
#> # A tibble: 4 x 2
#>       b     c
#>   <int> <int>
#> 1     1     2
#> 2     2     2
#> 3     1     1
#> 4     2     1
Created on 2021-08-17 by the reprex package (v2.0.0)
1 Answers

It is a different behavior compared to expand.grid from base R. But, the behavior is similar if we use do.call (or the similar one from purrr i.e. invoke - retired or exec )

library(purrr)
library(tidyr)
invoke(expand_grid, a)
exec(expand_grid, !!! a) # from @Mike Lawrence comments

-output

# A tibble: 4 x 2
      b     c
  <int> <int>
1     1     2
2     1     1
3     2     2
4     2     1

i.e. basically, expand.grid can work on list directly

expand.grid(a)
expand.grid(unclass(a))

whereas it is different behavior

 expand_grid(unclass(a))
# A tibble: 2 x 1
  `unclass(a)`
  <named list>
1 <int [2]>   
2 <int [2]>   
Related