AWK每列的RANK值 [英] RANK values per column with AWK
本文介绍了AWK每列的RANK值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
AWK中是否有一个RANK函数,可在单个文本文件中对每一列的值进行RANK排序(较高的值排在最前面)?期望这样:
Is there a RANK function in AWK that RANKs values per column in a single text file (higher value ranks on top)? Expecting this:
Original Results
A B C Result_A Result_B Result_C
8 5 4 1 2 1
4 7 3 2 1 2
2 3 4 3 3 1
我正在使用此AWK脚本,但仅对单个列进行排名.谁能引导我正确的方向?非常感谢.
I'm using this AWK script but only Ranks a single column. Can anyone guide me to the right direction? Very appreciated.
awk ' {
if(val!=$2){ rank++; }
printf("%s\t%s\t%s\n",rank,$1,$2)
val=$2
} ' <(sort -k2 -nr Original.txt) > Results.txt
推荐答案
You can try with gawk
and asorti
function Array-Sorting-Functions
awk 'BEGIN{OFS="\t"}
NR==1{
for(i=1; i<=NF; ++i) printf "Result_%s%s", $i, i==NF?ORS:OFS
next
}
{ for(i=1; i<=NF; ++i) M[i, NR-1]=$i }
END{
for(i=1; i<=NF; ++i){
delete d;
for(j=1; j<=NR-1; ++j) d[M[i,j]]
n = asorti(d, idx)
for(j=1; j<=n; ++j) rank[i, idx[j]] = n-j+1
}
for(j=1; j<=NR-1; ++j)
for(i=1; i<=NF; ++i)
printf "%s%s", rank[i, M[i,j]], i==NF?ORS:OFS
}
' original
你得到
Result_A Result_B Result_C
1 2 1
2 1 2
3 3 1
这篇关于AWK每列的RANK值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文