Hi All,
Thanks all for the continued support so far.
Today, I need to find the most occurring string/number(also called mode in statistics terminology) for each column in a data file (.csv type).
For one column of data(1.txt) like below
. The output is 1. ( As '1' appeared more number of times than other numbers)
But if I have multiple columns in a csv file, I am unable to do this task for each column printing the mode side by side. So I need an awk based loop script to fulfill my requirement.
Please let me know if my problem statement is not clear.
Thanks for your quick reply.
This script is perfectly fine for all files which have equal number of columns.
My challenge is to find 'mode' for files(.csv type) where
1) I don't know how many columns are there unless I open each file and check(very tedious task)
2) Printing the output side by side like mode_of_col1,mode_of_col2 etc.
For the first one i can count the number of columns in each file and feed into variable and loop through.
For the second one I can use the command
tr '\n' ' '
to transpose the output.
But all these change are making my code very lengthy and also I need to process many files (some times in 1000's).
Thats why I am looking for automatic looping script to print 'mode' for each column as well as looping to random number of columns.
Can you modify your script if you can ?
$ cat 1.txt
5,3,2,6
4,4,3,2
4,1,2,3
4,1,2,3
3,5,2,3
$ awk ' BEGIN { FS=OFS="," }
{ for (n = 1; n <= NF; n++) { a[n, $n]++ } }
END { for (n = 1; n <= NF; n++) {
x = 0
for (i in a) {
split(i, s, SUBSEP)
if (s[1] == n && a > x) {
x = a
y = s[2]
}
}
printf y (n==NF ? ORS : OFS)
}
} ' 1.txt > 2.txt
$ cat 2.txt
4,1,2,3
$
Note that if the mode is not unique, only one value is returned.
Thank you very much. You provided me the exact solution that I am looking for .
This script is taking only 1/10000 part of time that the previous script (which works on individual columns ).