Calculate average expression of a letter in a file using AWK

Viewed 40

I have a problem with a file. An example of the input file is the following

A   0.234
B   0.345
A   0.43
B   0.323
A   0.78
B   0.45
F   0.89
L   0.34
F   0.21
L   0.3
F   0.1

I need to calculate the average expression of each letter so the output will be similar to this

A   0.4813
B   0.3727
F   0.4
L   0.32

I already designed my code so it finds in the file the lines which contains only one letter and also calculate the proportion of each letter in the file. My question is if I can continue using that assumptions to calculate the average expression, because I don't know how to count each letter and add its corresponding value.

This is my code, which a partner from stackflow helped me with.

awk 'length($0)==1{a[$0]++} END{for(c in a) print c, a[c]/NR}'
2 Answers

You may use this awk:

awk '{sum[$1] += $2; ++freq[$1]} END {for (i in freq) printf "%s\t%.4f\n", i, sum[i]/freq[i]}' file

A   0.4813
B   0.3727
F   0.4000
L   0.3200

Even though you asked for awk specifically, why would you reinvented the wheel, when there are already plenty of tools designed for jobs like these, for instance GNU datamash:

datamash -Wsg 1 mean 2 < yourFile 

prints

A       0.48133333333333
B       0.37266666666667
F       0.4
L       0.32
Related