# Find the average of the letters in the list

I have some data this

dataABC = {
{"a", 1, 2, 3},
{"b", 1, 3, 5},
{"c", 1, 2, 1},
{"a", 1, 2, 3},
{"a", 1, 1, 1},
{"c", 1, 1, 1},
{"b", 2, 2, 2}
};


As you can see," a "," b" and "c" are followed by a series of numbers that represent their values.

For example,if {"a",1,2,3}

There are a lot of sublists like {"a",1,2,3} in the above data.

So what I want to do now is take the average of a, b, c with respect to value1, value2, value3,My English is not very good, and the following picture can better illustrate what I mean.

To find their average,I'm going to sort the data so that the "a", the "b", the "c" are all together,like this

dataABC1 = dataABC // Sort


Now what I'm going to do is I'm going to average them, and I don't know how to do that, right,I have tried using functions such as Select, Cases, etc. without success. What should I do?

GroupBy[dataABC, First -> Rest, Mean]


<|"a" -> {1, 5/3, 7/3}, "b" -> {3/2, 5/2, 7/2}, "c" -> {1, 3/2, 1}|>

Further, if required:

FlattenAt[#, -1] & /@ (List @@@
Normal@GroupBy[dataABC, First -> Rest, Mean])


{{"a", 1, 5/3, 7/3}, {"b", 3/2, 5/2, 7/2}, {"c", 1, 3/2, 1}}

More directly: (Mean of strings is a horrible idea but it works)

ArrayReduce[Mean, #, 1] & /@ GatherBy[dataABC, First]

• Cool. That's a great idea Commented Jan 7, 2023 at 10:23
• GroupBy[dataABC, First -> Rest, Mean] // KeyValueMap[List] also works : ) Commented Jan 7, 2023 at 16:35

A hand-writing way.

ans = <| |>;
cnt = <| |>;
dataABC = {
{"a", 1, 2, 3},
{"b", 1, 3, 5},
{"c", 1, 2, 1},
{"a", 1, 2, 3},
{"a", 1, 1, 1},
{"c", 1, 1, 1},
{"b", 2, 2, 2}
};
Table[
tail = Rest @ i;
{i, dataABC}
];
ans // KeyValueMap[#1 -> #2 / cnt[#1]&]


{"a" -> {1, 5/3, 7/3}, "b" -> {3/2, 5/2, 7/2}, "c" -> {1, 3/2, 1}}

Reap[MapApply[Sow[{##2},#1]&]@dataABC,_, Flatten[{#,Mean@#2}]&][[2]]

(*
5  7       3  5  7          3
{{a, 1, -, -}, {b, -, -, -}, {c, 1, -, 1}}
3  3       2  2  2          2

*)