I need to iterate through all possible realisations of a vector of length n
, each element being a number from 1 to g
. There are g^n
of these; g
is typically 3, while n
will be as large as I can reasonably get R to handle. On each realisation I'll calculate something f(z)
(where z
is the realisation) and add it to a running total (normalising constant of a distribution, if you want to know).
One example with n=10
would be c(1, 2, 3, 1, 2, 3, 1, 1, 2, 2)
.
I could do this with say some sort of expand.grid
cleverness and loop through each row, but is it possible to go through each realisation without holding them all simultaneously in memory?
With the expand.grid
(or similar) method where I would generate say a (g^n
) * n
matrix of z
possibilities, I would have to store them all in memory at once.
One option to avoid this is to iterate through all integers from 0
to g^n - 1
; convert this to a number in base g
(it will have n
characters from 0 to g-1
); and then add one to get a realisation of z
. However, I couldn't find a convenient (fast?) function to convert from an integer to a given base unless that base happened to be 2, 6, or 8.
So, does anyone know how I may convert an integer to a z
, or alternatively how I may conveniently construct a loop over all possible z
without having to store them all simultaneously at once?