# Pivot\_longer a multidimensional array

**URL:** <https://discourse.julialang.org/t/pivot-longer-a-multidimensional-array/80114>\
**Category:** General Usage\
**Tags:** array, dataframes\
**Created:** [April 27, 2022, 8:51am UTC](https://discourse.julialang.org/t/pivot-longer-a-multidimensional-array/80114 "2022-04-27T08:51:29Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Marco\_Repetto](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/marco_repetto/32/35451_2.png) [@Marco\_Repetto](https://discourse.julialang.org/u/Marco_Repetto)\
**Post date:** [April 27, 2022, 8:51am UTC](https://discourse.julialang.org/t/pivot-longer-a-multidimensional-array/80114/1 "2022-04-27T08:51:29Z")

</div>

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:

```julia
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:

```julia
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?

---

<div class="post-metadata">

**Author:** ![Christopher\_Fisher](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/christopher_fisher/32/26132_2.png) [@Christopher\_Fisher](https://discourse.julialang.org/u/Christopher_Fisher)\
**Post date:** [April 27, 2022, 9:15am UTC](https://discourse.julialang.org/t/pivot-longer-a-multidimensional-array/80114/2 "2022-04-27T09:15:40Z")

</div>

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

using Random  
Random.seed!(5411)

```julia
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
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
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

```

---

<div class="post-metadata">

**Author:** ![monopolynomial](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/monopolynomial/32/34782_2.png) [@monopolynomial](https://discourse.julialang.org/u/monopolynomial)\
**Post date:** [May 1, 2022, 1:09am UTC](https://discourse.julialang.org/t/pivot-longer-a-multidimensional-array/80114/3 "2022-05-01T01:09:36Z")

</div>

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