well I've written something that almost does the job, except it goes wrong on the very last line of the file. I read the file into an array and calculate the averages which I then put into a hash and then iterate through the array and lookup values from the hashes. I'm sure there's a more elegant way to do it though....

#!/usr/bin/perl # Usage: perl average_table.pl -i <input file> use strict; use warnings; use Getopt::Long; my $infile; my @fields; my @array; my @values; my %hash; my $add_fst; my @out; my @count; my $i=1; my @final; my %pval; my %fst; my $prev_loc; my $prev_pval; my $prev_fst; my $prev_join; GetOptions ( "infile=s" => \$infile, ); open INFILE, "<$infile" or die $!; @fields = <INFILE>; foreach (@fields){ @array = split(/\t+/, $_); chomp (@array); my ($name, $chr, $location, $gen, $dom, $pval, $fst) = @array[ +0..6]; my $join = "$chr-$location"; push (@values, $join, $pval); if ($location == $prev_loc){ $pval = $pval + $prev_pval; $fst = $fst + $prev_fst; $i++; } elsif ($location != $prev_loc) { my $pval_average = ($prev_pval / $i); my $fst_average = ($prev_fst / $i); my $join2 = "$prev_join\t$pval_average\t$fst_average"; $pval{$prev_join} = $pval_average; $fst{$prev_join} = $fst_average; push (@final, $join2); $i = 1; } $prev_loc = $location; $prev_pval = $pval; $prev_fst = $fst; $prev_join = $join; } foreach (@fields){ @out = split(/\t+/, $_); chomp (@out); my ($name, $chr, $location, $gen, $dom, $pval, $fst) = @ou +t[0..6]; my $join = "$chr-$location"; my $new_pval = $pval{$join}; my $new_fst = $fst{$join}; print $name."\t".$chr."\t".$location."\t".$gen."\t".$dom."\t". +$new_pval."\t".$new_fst."\n"; }

In reply to Re^4: average a column in tab-delimited file by garyboyd
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.