1

How would I approach calculating the quintiles from the csv file?

6
2
15
90
9
1
4
30
1

Output:

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

2 Answers2

1

An awk version that doesn't care about the values but the place when sorted on the value. 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:

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.

$ 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. Output for the latter version of OP's sample dataset:

1,1
1,1
2,2
4,3
6,3
9,4
15,4
30,5
90,5
James Brown
  • 31,411
  • 6
  • 31
  • 52
0

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:

#!/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)

Shawn
  • 28,389
  • 3
  • 10
  • 37