0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[AWK] 最大値、最小値、パーセンタイルの集計

Last updated at Posted at 2019-03-13

モチベーション

パーセンタイルを出したいとき、
Rなら

score <- seq(0,100)
summary(score)
quantile(score, 0.5)

などで一発ですが、これをAWKでやってみました。

seq 1 100 |
awk 'BEGIN{min="inf"}{
    if(max<$1) max=$1;
    if(min>$1) min=$1;
    percentile[NR]=$1}
    END{asort(percentile);
    print max,
    percentile[int(NR*0.75)],
    percentile[int(NR*0.5)],
    percentile[int(NR*0.25)],
    min
}'

工夫したところ

ついでのつもりでやった最小値で苦労しました…

minは何かしら入力データの最小値よりも大きな数値を指定しないといけないのですが、
具体的な数値を入力するには入力データの最大値がわかっていないといけません。
これは面倒なので取りうる値の最大値である"inf"を代入することにしました。

追記

asortがGNU拡張のため, POSIX準拠は以下のようになります.

yes | head -n 100 | awk '{print NR}' | # seqコマンドのPOSIX代替
sort -n |
awk 'BEGIN{min="inf"}{
    if(max<$1) max=$1;
    if(min>$1) min=$1;
    percentile[NR]=$1}
    END{
    print max,
    percentile[int(NR*0.75)],
    percentile[int(NR*0.5)],
    percentile[int(NR*0.25)],
    min
}'

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?