首页 > 解决方案 > tidyr::expand_grid() 未按预期运行;我错过了什么?

问题描述

这是我的代表:

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)

标签: rtidyversetidyr

解决方案


expand.grid与from相比,这是一种不同的行为base R。但是,如果我们使用do.call(或来自purrrie invoke-retired or的类似行为exec) ,行为是相似的

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

-输出

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

即基本上,expand.grid可以list直接工作

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

而这是不同的行为

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

推荐阅读