2016-11-09 24 views
2

猛砸大师最大值,我需要计算的最大值和百分位号码列表中的每个项目,用awk计算百分每个可变

aa 1 
ab 3 
aa 4 
ac 5 
aa 3 
ad 2 
ab 4 
ac 2 
ae 2 
ac 5 

预计输出

Item 90th percentile max value 
aa  3.8    4 
ab  3.9    4 
ac  5    5 
ad  2    2 
ae  2    2 

我能使用下面的得分和最大值,但不是百分点。

awk '{ 
item[$1]++; 
count[$1]+=$2; 
max[$1]=$2; 
percentile[$1,.9]=$2 
} 
END{ 
for (var in item) 
print var,count[var],max[var],percentile[var] 
} 
' 

请建议。

+1

你在期待'百分[$ 1,0.9] = $ 2'办? –

+3

你用什么方法计算百分位数?线性插值 ?最近排名?你在bash中实现了一个函数吗? – Aserre

+0

@jas他们是1,3和4. – dood

回答

2

百分比计算来自Statistics for Dummies 2nd ed。 :)。在了GNU AWK:

$ cat mnp.awk 
BEGIN { 
    PROCINFO["sorted_in"]="@ind_num_asc" # for order in output 
    if(p=="")        # if p not defined it's median 
     p=0.5 
    else 
     p=p/100       # if 90th percentile: p=0.9 
} 
{ 
    v[$1][NR]=$2       # values stored per keyword. NR for unique 
    if($2>m[$1])       # find max val 
     m[$1]=$2 
} 
END { 
    for(i in v) {       # for all keywords 
     n=asort(v[i])      # sort values, n is count 
     prc=p*n;       # percentile figuration 
     if(prc==int(prc)) 
      w=(v[i][prc]+v[i][prc+1])/2 
     else 
      w=v[i][int(prc)+1] 
     print i, m[i], w     # print keyword, max and nth value 
    } 
} 

运行:

$ awk -p=90 -f mnp.awk data.txt 
aa 4 4 
ab 4 4 
ac 5 5 
ad 2 2 
ae 2 2 

TODO:如果数据文件进行了排序,这可以简化,而不是所有的数据都需要被存储到内存中。

+0

这不是OP公布的预期输出。 – dood

+1

@dood是的。 OP会给出他想要的百分位数的定义。引用维基百科的百分位数:_没有百分位数的标准定义,但是当观测数量非常大时,所有的定义都会产生相似的结果。我使用的定义来自_Statistics for Dummies_第2版。 –

0

这里是一个完美的解决方案,我发现在互联网附近浮动寻找最大值:

{ 
    max[$1] = !($1 in max) ? $2 : ($2 > max[$1]) ? $2 : max[$1] 
} 
END { 
    for (i in max) 
    print i, max[i] 
} 

输出:

ab 4 
ac 5 
ad 2 
ae 2 
aa 4 
+1

你只需要'max [$ 1] =((最大$ 1)&&(max [$ 1]> $ 2)?max [$ 1]:$ 2)'避免负面('!')并重复(设置为'$ 2'在多个位置)语法。 –

0

datamash是一个可爱的工具,虽然它不支持过度的部分。

$ datamash -W --sort --group=1 max 2 min 2 < INPUT 
aa 4 1 
ab 4 3 
ac 5 2 
ad 2 2 
ae 2 2 

它支持以下操作

File operations: 
    transpose, reverse 
Numeric Grouping operations: 
    sum, min, max, absmin, absmax 
Textual/Numeric Grouping operations: 
    count, first, last, rand 
    unique, collapse, countunique 
Statistical Grouping operations: 
    mean, median, q1, q3, iqr, mode, antimode 
    pstdev, sstdev, pvar, svar, mad, madraw 
    pskew, sskew, pkurt, skurt, dpo, jarque