Mean age of people
You need EmpiricalDistribution
:
data = {14, 15, 16, 22, 24, 25};
weights = {1, 1, 3, 2, 2, 5};
\[ScriptCapitalD] = EmpiricalDistribution[weights -> data];
Expectation[x, x \[Distributed] \[ScriptCapitalD]]
(* 21 *)
values = {14, 15, 16, 22, 24, 25};
weights = {1, 1, 3, 2, 2, 5};
You can also use WeightedData
:
Mean @ WeightedData[values, weights]
21
or use Mean
with EmpiricalDistribution
:
Mean @ EmpiricalDistribution[weights -> values]
21
Both methods also work with symbolic input:
values = Array[Subscript[x, #] &, 5];
weights = Array[Subscript[w, #] &, 5];
Mean @ WeightedData[values, weights]
TeXForm @ %
$$\frac{w_1 x_1+w_2 x_2+w_3 x_3+w_4 x_4+w_5 x_5}{w_1+w_2+w_3+w_4+w_5}$$
Mean @ EmpiricalDistribution[weights -> values] // Together // TeXForm
$$\frac{w_1 x_1+w_2 x_2+w_3 x_3+w_4 x_4+w_5 x_5}{w_1+w_2+w_3+w_4+w_5}$$
These are all quite fancy solutions so far. For beginners' sake, I'd like to add a somewhat more elementary one that uses somewhat more universal tools:
ages = {14, 15, 16, 22, 24, 25};
counts = {1, 1, 3, 2, 2, 5};
ages.counts/Total[counts]
21
The .
(a.k.a. Dot
) computes this sum
Sum[ages[[i]] counts[[i]], {i, 1, Length[ages]}]
and Total
computes this one:
Sum[counts[[i]], {i, 1, Length[ages]}]
So one can also obtain the result as follows:
Sum[ages[[i]] counts[[i]], {i, 1, Length[ages]}]/Sum[counts[[i]], {i, 1, Length[counts]}]
But Dot
and Total
are typically faster because they rely on very optimized libraries in the background. And of course, it is also shorter to type.