Just curious if there is anything out there - an expand.grid
like function which would return a matrix rather than a data frame?
Expected output (but not the expected way to get there)
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
Created on 2020-03-25 by the reprex package (v0.3.0)
If you'd like to do it faster, you could use data.table
's CJ
function and data.table::as.matrix
.
library(data.table)
system.time(matrix <- as.matrix(CJ(1:10000,1:10000)))
user system elapsed
1.215 0.486 1.709
system.time(rep.matrix <- cbind(rep(1:10000,each=10000),rep(1:10000,times=10000)))
user system elapsed
3.193 0.406 3.625
system.time(matrix <- as.matrix(expand.grid(1:10000,1:10000)))
user system elapsed
3.506 0.880 4.405
We can use crossing
from tidyr
library(tidyr)
as.matrix(crossing(v1 = 1:4, v2= 1:4, v3 = 1:3))
If we need to directly create a matrix, use
cbind(rep(1:4, each = 4), rep(1:4, 4))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With