r - 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)
解决方案
expand.grid
与from相比,这是一种不同的行为base R
。但是,如果我们使用do.call
(或来自purrr
ie 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]>
推荐阅读
- reactjs - 如何在 Nextjs 中导入两个组件
- docker - Gitlab CI。来自守护进程的错误响应:没有这样的图像
- protocol-buffers - 添加新消息后的 Proto2 编码/解码问题
- c - 为什么我在将 for 循环的乘积声明为 C 中的变量时收到此错误“错误:预期表达式”
- python - 当您知道嵌套键时访问嵌套字典?
- c++ - /d2vzeroupper MSVC 编译器优化标志在做什么?
- flutter - 我怎样才能制作这个 rtl - 颤动
- python - Numpy 获取具有当前值的邻居索引的最快方法(洪水填充)
- c# - 如何避免使用 EF Core 进行保存时的实体跟踪?
- python - 将 860 页从 PDF 转换为 jpeg,仅转换 175 页。使用 python wand.image