awk 列的中位数 [英] median of column with awk

查看:30
本文介绍了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:

到目前为止我所拥有的是:

What I have so far is:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆