robertevansanders robertevansanders - 3 months ago 18
R Question

expand grid for an arbitrary number of vectors in R

I want to use expand.grid in R but have it work over two pre-specified vectors and an arbitrary remaining amount:

example, two vectors d and w, and 3 vectors of length 4:

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


The problem is that it thinks that the last thing is one object, and I want it to have Var3, Var4, and Var5. Instead, we 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 I do it alone without the first two vectors, it 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
...

Answer

If you check ?expand.grid and take a look at the parameters, it says:

...
vectors, factors or a list containing these.

It doesn't seem like it accepts mixed vectors and lists. Concatenating the vectors and list to make a single list as parameter will 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