# coding advice on replacing nested for loops

I have a problem where I have a number of vectors (how many vectors unknown in advance) each of which has a different number of elements (also unknown in advance). I want to walk though all the combinations of values, doing an operation for each combination. (The vectors can be lists if that's more convenient.)

If I knew there were three vectors I could write nested for loops, something like this:

``````for (i in seq_along(x))
for (j in seq_along(y))
for (k in seq_along(z))
# do something more interesting than the next line
cat(x[i],y[j],z[k])
``````

But I don't know how many vectors there will be.

I suspect there is an obvious solution to this. I just don't see it. Any suggestions?

Depending on what your actual calculation is, you might find expand.grid to be a useful function. You can pass it either the individual vectors or a list containing the vectors.

``````x <- 1:2
y <- 1:3
z <- 11:12
DF <- expand.grid(x,y,z)
DF
Var1 Var2 Var3
1     1    1   11
2     2    1   11
3     1    2   11
4     2    2   11
5     1    3   11
6     2    3   11
7     1    1   12
8     2    1   12
9     1    2   12
10    2    2   12
11    1    3   12
12    2    3   12

DataList <- list(x,y,z)
expand.grid(DataList)
Var1 Var2 Var3
1     1    1   11
2     2    1   11
3     1    2   11
4     2    2   11
5     1    3   11
6     2    3   11
7     1    1   12
8     2    1   12
9     1    2   12
10    2    2   12
11    1    3   12
12    2    3   12
``````

@FJCC Brilliant! Thanks much.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.