matrix - expand grid for an arbitrary number of vectors in R -


i want use expand.grid in r have work on 2 pre-specified vectors , arbitrary remaining amount:

example, 2 vectors d , w, , 3 vectors of length 4:

m = expand.grid(d = 1:3, w = 1:3, rep(list(1:4),(3))) 

the problem thinks last thing 1 object, , want have var3, var4, , var5. instead, get:

    m    d w       var3 1  1 1 1, 2, 3, 4 2  2 1 1, 2, 3, 4 3  3 1 1, 2, 3, 4 4  1 2 1, 2, 3, 4 5  2 2 1, 2, 3, 4 6  3 2 1, 2, 3, 4 7  1 3 1, 2, 3, 4 

interestingly when alone without first 2 vectors, can expandgrid:

m = expand.grid(rep(list(1:4),(3)))       var1 var2 var3 1     1    1    1 2     2    1    1 3     3    1    1 4     4    1    1 5     1    2    1 6     2    2    1 7     3    2    1 ... 

if check ?expand.grid , take @ parameters, says:

...
vectors, factors or list containing these.

it doesn't seem accepts mixed vectors , lists. concatenating vectors , list make single list parameter work:

m = expand.grid(c(list(d = 1:3, w = 1:3), rep(list(1:4), 3))) m #    d w var3 var4 var5 #1   1 1    1    1    1 #2   2 1    1    1    1 #3   3 1    1    1    1 #4   1 2    1    1    1 #5   2 2    1    1    1 #6   3 2    1    1    1 # ... 

Comments