Calculate average for rows in a text file

Dear Gurus,

I have tab-delimited text files with matrix containing values. The first column is a identifier and other columns have the corresponding values. I would like to calculate the average value (total number/number of entries) for all entries from 2nd column to the last column in row wise.

For example,

file 1
Id per1 per2 per3 
12 34.56 -0.54 12.5 
13 0.15 -0.06 0.05 
14 0.67 0.12 0.09 
15 0.05 0.06 -0.07

Please note some values are negative numbers. I want to have a result file

ID avg
12 15.50
13 0.14 
14 0.88
15 0.04

Can somebody suggest a script to deal with this? Thanks a lot indeed.

awk 'NR==1{next}
       {printf("%s\t", $1  
        printf("%.2f\n", ($2 + $3 + $4)/3 }'  file1 > newfile
1 Like

thanks a lot for the script Jim. It works if I have three columns to calculate. How can do it if the file has more than 100 columns? Is there a way to mention the range like column 1 to column 150 for example?

Best to ask for what you need on the first go :smiley:

awk 'NR==1 { next }
        { T=0
           for(N=2; N<=NF; N++) T+=$N;
           T/=(NF-1)
           print $1, T }' file > outfile

That will calculate all columns from the second column to the last. You could also have FIRST=2, LAST=150, and for(N=FIRST; N<=LAST; N++), then divide by (FIRST-LAST)

1 Like