Pivot_longer a multidimensional array

I would like to transform a multidimensional array into a matrix of indexes and with the last column being the value itself. In a similar fashion to what pivot_longer does in R.

As an example, this 3-D array:

rand(2,2,2)

2×2×2 Array{Float64, 3}:
[:, :, 1] =
 0.815842  0.251812
 0.328409  0.474825

[:, :, 2] =
 0.315777  0.707802
 0.427597  0.308795

will become:

3×4 Matrix{Float64}:
 1.0  1.0  1.0  0.815842
 1.0  1.0  2.0  0.315777
 1.0  2.0  1.0  0.251812
...

One strategy may be to use list comprehension in the array itself, but is there a more straightforward way?

I’m sure there are more elegant solutions, but here is one that works:

using Random
Random.seed!(5411)

function pivot_longer(x)
    output = zeros(length(x), length(size(x))+1)
    for (i,idx) in enumerate(CartesianIndices(x))
        output[i,:] = [idx.I... x[idx]]
    end
    return output
end


x = rand(2, 2, 2)

y = pivot_longer(x)

output

julia> x
2×2×2 Array{Float64, 3}:
[:, :, 1] =
 0.93722   0.283684
 0.988042  0.183431

[:, :, 2] =
 0.970431  0.842597
 0.473857  0.121432
julia> y
8×4 Matrix{Float64}:
 1.0  1.0  1.0  0.93722
 2.0  1.0  1.0  0.988042
 1.0  2.0  1.0  0.283684
 2.0  2.0  1.0  0.183431
 1.0  1.0  2.0  0.970431
 2.0  1.0  2.0  0.473857
 1.0  2.0  2.0  0.842597
 2.0  2.0  2.0  0.121432
2 Likes

pivot_longer in R is for datasets, InMemoryDatasets package’s transpose does that.