# Conditional statistics over 1 dimension of a multidimensional array

**URL:** https://discourse.julialang.org/t/conditional-statistics-over-1-dimension-of-a-multidimensional-array/69944
**Category:** General Usage
**Tags:** statistics, arrays
**Created:** [October 17, 2021, 7:58pm UTC](https://discourse.julialang.org/t/conditional-statistics-over-1-dimension-of-a-multidimensional-array/69944 "2021-10-17T19:58:42Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![Chiil](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chiil/32/27474_2.png) [@Chiil](https://discourse.julialang.org/u/Chiil)
#### Post date: [October 17, 2021, 7:58pm UTC](https://discourse.julialang.org/t/conditional-statistics-over-1-dimension-of-a-multidimensional-array/69944/1 "2021-10-17T19:58:42Z")

</div>

I would like to compute conditional statistics over one dimension of a two-dimensional array. I have an array `a` and I would like to compute a mean over the first dimension, taking into account only the cells where `b < 0.5`. With `numpy` this is easy with masked arrays, but I haven’t found an Julia equivalent for this. What is the Julian way of solving this?

```julia
using Statistics

nx = 16
nz = 8

a = rand(nx, nz)
b = rand(nx, nz)

# This gives a vertical profile of 8 layers. This is the right shape,
# but without the mask applied.
a_prof = mean(a, dims=1)
println(a_prof)

# This gives a scalar, but I would like a vertical profile of 8 layers,
# with only the indices where b < 0.5 in the computation.
a_prof_b = mean(a[b .< 0.5], dims=1)
println(a_prof_b)

```

---

<div class="post-metadata">

### Author: ![rafael.guerra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rafael.guerra/32/216610_2.png) [@rafael.guerra](https://discourse.julialang.org/u/rafael.guerra)
#### Post date: [October 17, 2021, 8:19pm UTC](https://discourse.julialang.org/t/conditional-statistics-over-1-dimension-of-a-multidimensional-array/69944/2 "2021-10-17T20:19:38Z")

</div>

One suggestion:

```julia
a_prof_b = [mean(a[b[:,i] .< 0.5, i]) for i in 1:size(a,2)]

```

---

<div class="post-metadata">

### Author: ![aplavin](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/aplavin/32/222056_2.png) [@aplavin](https://discourse.julialang.org/u/aplavin)
#### Post date: [October 17, 2021, 8:39pm UTC](https://discourse.julialang.org/t/conditional-statistics-over-1-dimension-of-a-multidimensional-array/69944/3 "2021-10-17T20:39:50Z")

</div>

Looks like your arrays are related and have corresponding indices, so it makes sense to keep and use them together:

```julia
using SplitApplyCombine
using StructArrays

# reproduce your simple mean of a with SplitApplyCombine functions:
map(splitdims(a, 2)) do x
	mean(x)
end

# combine a and b arrays to use them together:
AB = StructArray(; a, b)

# compute the desired conditional mean:
map(splitdims(AB, 2)) do x
	mean(x.a[x.b .< 0.5])
end

```
