2016-10-26 299 views
0

我正在嘗試創建一個腳本,該腳本可以計算多個行的平均值計算多個列的平均值

這個數字將取決於我擁有的樣本數量,因樣本數量而異。

這些文件的一個例子是在這裏:

24 1 2.505 
24 2 0.728 
24 3 0.681 
48 1 2.856 
48 2 2.839 
48 3 2.942 
96 1 13.040 
96 2 12.922 
96 3 13.130 
192 1 50.629 
192 2 51.506 
192 3 51.016 

平均值在第3列和,計算

第二列表示樣品的3在該特定的數量,案件。

因此,我應該在這裏獲得4值

每3行一個平均值。

我已經試過類似:

count=3; 
total=0; 

for i in $(awk '{ print $3; }' ${file}) 
do 
    for j in 1 2 3 
    do 
    total=$(echo $total+$i | bc) 
    done 
    echo "scale=2; $total/$count" | bc 
done 

但它不給我正確的答案,而不是我想它計算每組的三排的平均值。

平均值被計算在第3列和

第二列表示樣品,3在該特定情況下的數量。

因此,我應該在這裏獲得4值

每3行一個平均值。

我已經試過類似:

count=3; 
total=0; 

for i in $(awk '{ print $3; }' ${file}) 
do 
    for j in 1 2 3 
    do 
    total=$(echo $total+$i | bc) 
    done 
    echo "scale=2; $total/$count" | bc 
done 

但它不給我正確的答案,而不是我想它計算每組的三排的平均值。

預計輸出

24 1.3046  
48 2.879  
96 13.0306  
192 51.0503  
+1

讓我看看我是否理解你。你想要三列的第三列的平均值?預期產出是多少? – VM17

+1

我想玩猜謎遊戲! –

回答

1

顯然我對這個問題提出了第三種觀點。在awk中:

$ awk 'NR>1 && $1!=p{print p, s/c; c=s=0} {s+=$3;c++;p=$1} END {print p, s/c}' file 
24 1.30467 
48 2.879 
96 13.0307 
192 51.0503 
1

您可以使用以下awk腳本:

awk '{t[$2]+=$3;n[$2]++}END{for(i in t){print i,t[i]/n[i]}}' file 

輸出:

1 17.2575 
2 16.9988 
3 16.9423 

這是更好,因爲在它的意見多行腳本解釋說:

# On every line of input 
{ 
    # sum up the value of the 3rd column in an array t 
    # which is is indexed by the 2nd column 
    t[$2]+=$3 
    # Increment the number of lines having the same value of 
    # the 2nd column 
    n[$2]++ 
} 
# At the end of input 
END { 
    # Iterate through the array t 
    for(i in t){ 
     # Print the number of samples along with the average 
     print i,t[i]/n[i] 
    } 
} 
+0

我們對這個問題顯然有不同的理解。 – VM17

+0

我們希望OP能提供預期的輸出。 – hek2mgl

+0

@ hek2mgl很好解釋,謝謝! – Manolete