Here is a solution I came up with. The same general idea - but uses the module List::Util, (part of perl core since v5.7.3), to get the sum of the 2 columns.

I compared the join of (chr, location), to determine the end of a run instead of just location by itself.

#!/usr/bin/perl use strict; use warnings; use List::Util qw/ sum /; chomp(my $line = <DATA>); my $prev_chr_loc = join "-", (split /\t/, $line)[1,2]; my @lines = $line; while (my $line = <DATA>) { chomp $line; my $chr_loc = join "-", (split /\t/, $line)[1,2]; if ($chr_loc eq $prev_chr_loc) { push @lines, $line; } else { print "$_\n" for compute_avg( @lines ); @lines = $line; } $prev_chr_loc = $chr_loc; } print "$_\n" for compute_avg( @lines ); sub compute_avg { my @lines = @_; my $avg_col5 = sprintf "%.9f", sum(map {(split /\t/)[5]} @lines) / @lines; my $avg_col6 = sprintf "%.9f", sum(map {(split /\t/)[6]} @lines) / @lines; for (@lines) { my ($c5,$c6) = (split /\t/)[5,6]; s/$c5\t$c6$/$avg_col5\t$avg_col6/; } return @lines; }

Update: Redid substitution for closer spec.


In reply to Re^5: average a column in tab-delimited file by Cristoforo
in thread average a column in tab-delimited file by garyboyd

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.