Play the `expand.grid` function from R in Julia

expand.grid- A very convenient function in Rto calculate all possible combinations from several lists. Here's how it works:

> x = c(1,2,3)
> y = c("a","b")
> z = c(10,12)
> d = expand.grid(x,y,z)
> d
   Var1 Var2 Var3
1     1    a   10
2     2    a   10
3     3    a   10
4     1    b   10
5     2    b   10
6     3    b   10
7     1    a   12
8     2    a   12
9     3    a   12
10    1    b   12
11    2    b   12
12    3    b   12

How can I play this feature in Julia?

+4
source share
2 answers

Thanks to @Henrik's comment:

x = [1,2,3]
y = ["a","b"]
z = [10,12]
d = collect(Iterators.product(x,y,z))

Here is another list comprehension solution

reshape([ [x,y,z]  for x=x, y=y, z=z ],length(x)*length(y)*length(z))
+2
source

Here is my complete (?) General solution using recursion, varargs and splatting:

function expandgrid(args...)
    if length(args) == 0
        return Any[]
    elseif length(args) == 1
        return args[1]
    else
        rest = expandgrid(args[2:end]...)
        ret  = Any[]
        for i in args[1]
            for r in rest
                push!(ret, vcat(i,r))
            end
        end
        return ret
    end
end

eg = expandgrid([1,2,3], ["a","b"], [10,12])
@assert length(eg) == 3*2*2
@show eg

This gives an array of arrays, but you could combine this into a matrix trivially if that is what you wanted.

+2
source

All Articles