awk列的中位数 [英] median of column with awk
本文介绍了awk列的中位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用AWK计算一列数值数据的中位数?
How can I use AWK to compute the median of a column of numerical data?
我可以想到一个简单的算法,但是我似乎无法对其进行编程:
I can think of a simple algorithm but I can't seem to program it:
到目前为止,我有:
sort | awk 'END{print NR}'
这给了我列中元素的数量.我想用它来打印特定的行(NR/2)
.如果NR/2
不是整数,则四舍五入到最接近的整数,即中位数,否则取(NR/2)+1
和(NR/2)-1
的平均值.
And this gives me the number of elements in the column. I'd like to use this to print a certain row (NR/2)
. If NR/2
is not an integer, then I round up to the nearest integer and that is the median, otherwise I take the average of (NR/2)+1
and (NR/2)-1
.
推荐答案
此awk
程序假定一列数字排序的数据:
This awk
program assumes one column of numerically sorted data:
#/usr/bin/env awk
{
count[NR] = $1;
}
END {
if (NR % 2) {
print count[(NR + 1) / 2];
} else {
print (count[(NR / 2)] + count[(NR / 2) + 1]) / 2.0;
}
}
样品用量:
sort -n data_file | awk -f median.awk
这篇关于awk列的中位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文