5
$\begingroup$

I have a list:

list = {{17, 2}, {11.55, 3}, {18.5, 1}, {14.2, 1}, {14.25, 2}, {11.5,3}, {15, 2}, {11, 3},{10.8, 3}};

I wish to calculate:

  (17*2+11.5*3+18.5*1+14.2*1+14.25*2+...+10.8*3)/(2+3+1+2+...+3)

How can I use list manipulation?

$\endgroup$
1

4 Answers 4

9
$\begingroup$

To make @I.M.'s comment explicit:

list = {{17, 2}, {11.55, 3}, {18.5, 1}, {14.2, 1}, {14.25, 2},
        {11.5, 3}, {15, 2}, {11, 3}, {10.8, 3}};

data = WeightedData @@ Transpose[list];

Mean[data]
(*    12.9875    *)

Variance[data]
(*    6.53654    *)
$\endgroup$
1
  • $\begingroup$ WeightedData is a fruitful function I have not known it!! Thank you so much for your answer. It was so interesting!!! $\endgroup$ Sep 14, 2021 at 16:00
3
$\begingroup$

Using list manipulation (and showing the steps):

list = {{17, 2}, {11.55, 3}, {18.5, 1}, {14.2, 1}, {14.25, 2}, {11.5, 
    3}, {15, 2}, {11, 3}, {10.8, 3}};

Times @@@ list

{34, 34.65, 18.5, 14.2, 28.5, 34.5, 30, 33, 32.4}

Total@(Times @@@ list)

259.75

Total@list[[All, 2]]

20

Putting it together in one step:

Total@(Times @@@ list)/Total@list[[All, 2]]

12.9875

Of course, this is why functions are written, i.e., to reduce the work. Note that to find variance and stdev using list manipulation would become difficult and error-prone and the WeightedData approach is more suitable.

$\endgroup$
3
$\begingroup$

WeightedData is both convenient and efficient. For the sake of variety you can also do:

wA = #.Normalize[#2, Total] & @@ Transpose @ # &;
wA @ list
12.9875

and for fun:

enter image description here

☺ = #.#2/(+## & @@ #2) & @@ (#\[Transpose]) &;
☺ @ list
12.9875
$\endgroup$
2
$\begingroup$

Similar to Syed, also the numbers inside the list can be used also #1, #2

Total[{#1*#2} & @@@ list]/Total[list[[All, 2]]]

12.98

$\endgroup$
1
  • 1
    $\begingroup$ I like your answer!!! using # in functions is very interesting and amazing $\endgroup$ Sep 14, 2021 at 16:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.