是否有类似 Expand.grid 的矩阵输出函数

Tje*_*ebo 5 r

只是好奇是否有任何东西 - 一个expand.grid类似的函数会返回一个矩阵而不是一个数据框?

预期的输出(但不是达到预期的方式

as.matrix(expand.grid(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
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.3.0)于 2020-03-25 创建

akr*_*run 3

我们可以使用crossing来自tidyr

library(tidyr)
as.matrix(crossing(v1 = 1:4, v2= 1:4, v3 = 1:3))
Run Code Online (Sandbox Code Playgroud)

如果我们需要直接创建一个矩阵,使用

cbind(rep(1:4, each = 4), rep(1:4, 4))
Run Code Online (Sandbox Code Playgroud)