简体   繁体   English

用 bash 计算五分位数

[英]Calculating quintiles with bash

How would I approach calculating the quintiles from the csv file?我将如何从 csv 文件中计算五分位数?

6
2
15
90
9
1
4
30
1

Output: Output:

6,3
2,2
15,4
90,5
9,4
1,1
4,3
30,5
1,1

An awk version that doesn't care about the values but the place when sorted on the value.一个 awk 版本,它不关心值,而是按值排序时的位置。 The quintilies are defined on the earlier revision of your question:五分位数是在您问题的早期版本中定义的:

awk '
BEGIN {
    FS=OFS=","
}
{
    a[NR]=$0
}
END {
    for(i=1;i<=int(0.2*NR);i++)
        b[i]=1
    for(;i<=(0.4*NR);i++)
        b[i]=2
    for(;i<=(0.6*NR);i++)
        b[i]=3
    for(;i<=(0.8*NR);i++)
        b[i]=4
    for(;i<=NR;i++)
        b[i]=5
    for(i=1;i<=NR;i++)
        print a[i],b[i]
}' <(sort -t, -k3n file)

Output: Output:

k,l,1,1
q,r,1,2     < this differs
c,d,2,2
m,n,4,3
a,b,6,3
i,j,9,4
e,f,15,4
o,p,30,5
g,h,90,5

Update: A more compact version that still relies on the position of the value in ordered list of values but keeps equal values in the same quintile.更新:一个更紧凑的版本,它仍然依赖于值的有序列表中的值的 position,但在相同的五分位数中保持相等的值。

$ awk '
BEGIN {
    FS=OFS=","
}
{
    a[NR]=$0                     # hash all values index on order #
}
END {                            # after all values are hashed
    for(i=1;i<=NR;i++) {         # loop thru them all 
        j+=(i>j*0.2*NR&&a[i]!=p) # figuring out current quintile
        print a[i],j             # output
        p=a[i]
    }
}' <(sort -n file)

With GNU awk you could define PROCINFO["sorted_in"]="@val_num_asc" and lose the sort .使用 GNU awk 您可以定义PROCINFO["sorted_in"]="@val_num_asc"并丢失sort Output for the latter version of OP's sample dataset: Output 用于 OP 样本数据集的后一个版本:

1,1
1,1
2,2
4,3
6,3
9,4
15,4
30,5
90,5

Here's a shell script that uses sqlite3 to compute the quintiles with its ntile() window function, which divides the values up into a given number of groups:这是一个 shell 脚本,它使用 sqlite3 用它的ntile() window function 计算五分位数,它将值分成给定数量的组:

#!/bin/sh
printf "%s\n" \
       "CREATE TABLE data(a, b, c INTEGER);" \
       ".import '$1' data" \
       "SELECT a, b, c, ntile(5) OVER (ORDER BY c) FROM data ORDER BY rowid;" |
    sqlite3 -csv -batch -noheader

Example:例子:

$ ./quintile.sh input.csv
a,b,6,3
c,d,2,2
e,f,15,4
g,h,90,5
i,j,9,3
k,l,1,1
m,n,4,2
o,p,30,4
q,r,1,1

(This does require sqlite3 version 3.25 or newer) (这确实需要sqlite3版本 3.25 或更高版本)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM