linux awk命令實現對數據的每一列進行求和、求平均


1、測試數據

root@PC1:/home/test# ls
test.txt
root@PC1:/home/test# cat test.txt
3 4 2 9
1 3 5 4
3 7 8 4
2 3 4 6

 

2、對每一列數據進行求和

root@PC1:/home/test# ls
test.txt
root@PC1:/home/test# cat test.txt
3 4 2 9
1 3 5 4
3 7 8 4
2 3 4 6
root@PC1:/home/test# for i in `head -n 1 test.txt | awk '{print NF}' | xargs seq`; do awk -v a=$i 'BEGIN{sum = 0} {sum += $a} END{print sum}' test.txt >> sum.txt; done
root@PC1:/home/test# ls
sum.txt  test.txt
root@PC1:/home/test# cat sum.txt ##求和結果保存為列的形式 9
17
19
23
root@PC1:/home/test# paste -d " " -s sum.txt   ## 將列的形式轉換為行的形式
9 17 19 23

 

3、對每一列求平均

root@PC1:/home/test# ls
test.txt
root@PC1:/home/test# cat test.txt
3 4 2 9
1 3 5 4
3 7 8 4
2 3 4 6
root@PC1:/home/test# for i in `head -n 1 test.txt | awk '{print NF}' | xargs seq `; do awk -v a=$i 'BEGIN{sum = 0} {sum += $a} END {print sum/NR}' test.txt >> mean.txt; done
root@PC1:/home/test# ls
mean.txt  test.txt
root@PC1:/home/test# cat mean.txt
2.25
4.25
4.75
5.75
root@PC1:/home/test# paste -d " " -s mean.txt ## 每一列求平均結果 2.25 4.25 4.75 5.75

 

4、R語言實現

dir()
dat <- read.table("test.txt", header = F)
dat
apply(dat, 2, sum)
apply(dat, 2, mean)
> dir()
[1] "test.txt"
> dat <- read.table("test.txt", header = F) ## 讀取測試數據 > dat
  V1 V2 V3 V4
1  3  4  2  9
2  1  3  5  4
3  3  7  8  4
4  2  3  4  6
> apply(dat, 2, sum) ## 求每一列的和
V1 V2 V3 V4 
 9 17 19 23 
> apply(dat, 2, mean) ## 求每一列的平均數
  V1   V2   V3   V4 
2.25 4.25 4.75 5.75 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM