1

I have a file with 2 columns and many rows. I would like to calculate the mean for each column for odd and even lines independantly, so that in the end I would have a file with 4 values: 2 columns with odd and even mean. My file looks like this:

2 4 4 4 6 8 3 5 6 9 2 1

In the end I would like to obtain a file with the mean of 2,6,6 and 4,3,2 in the first column and the mean of 4,8,9 and 4,5,1 in the second column, that is:

4.66 7 3 3.33

If anyone could give me some advice I'd really appreaciate it, for the moment I'm only able to calculate the mean for all rows (not even and odd). Thank you very much in advance!

3 Answers3

2

This is an awk hardcoded example but you can get the point :

awk 'NR%2{e1+=$1;e2+=$2;c++;next}
     {o1+=$1;o2+=$2;d++}
     END{print e1/c"\t"e2/c"\n"o1/d"\t"o2/d}' your_file
4.66667 7
3       3.33333
Juan Diego Godoy Robles
  • 14,447
  • 2
  • 38
  • 52
1

A more generalized version of Juan Diego Godoy's answer. Relies on GNU awk

gawk '
    {
        parity = NR % 2 == 1 ? "odd" : "even"
        for (i=1; i<=NF; i++) {
            sum[parity][i] += $i
            count[parity][i] += 1
        }
    }
    function result(parity) {
        for (i=1; i<=NF; i++)
            printf "%g\t", sum[parity][i] / count[parity][i]
        print ""
    }
    END { result("odd"); result("even") }
'
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
0

This answer uses Bash and bc. It assumes that the input file consists of only integers and that there is an even number of lines.

#!/bin/bash
while read -r oddcol1 oddcol2; read -r evencol1 evencol2
do
    (( oddcol1sum += oddcol1 ))
    (( oddcol2sum += oddcol2 ))
    (( evencol1sum += evencol1 ))
    (( evencol2sum += evencol2 ))
    (( count++ ))
done < inputfile

cat <<EOF | bc -l
    scale=2
    print "Odd Column 1 Mean: "; $oddcol1sum / $count
    print "Odd Column 2 Mean: "; $oddcol2sum / $count
    print "Even Column 1 Mean: "; $evencol1sum / $count
    print "Even Column 2 Mean: "; $evencol2sum / $count
EOF

It could be modified to use arrays to make it more flexible.

Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439