Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an expand.grid like function with matrix output

Tags:

r

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)

like image 559
tjebo Avatar asked Mar 25 '20 17:03

tjebo


2 Answers

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
like image 140
Ian Campbell Avatar answered Sep 30 '22 12:09

Ian Campbell


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))
like image 45
akrun Avatar answered Sep 30 '22 12:09

akrun