If the rows are not ordered by pos then you need to keep a total for each bin. Consider:

#!/usr/bin/perl use warnings; use strict; use 5.010; my $binSize = 20; my %binTotals; while (<DATA>){ chomp; my ($chr, $pos, $coverage) = split /\t/; $binTotals{int(($pos - 1) / $binSize)} += $coverage; } printf "%4d %d\n", 20 * (1 + $_), $binTotals{$_} for sort {$a <=> $b} +keys %binTotals; __DATA__ chr 1 2 chr 4 2 chr 7 5 chr 22 5 chr 24 6 chr 38 10 chr 44 10 chr 50 20 chr 57 25 chr 60 30 chr 65 30

Prints:

20 9 40 21 60 85 80 30

and actually that is a lot cleaner than code that assumes the rows ore ordered so doesn't need to accumulate totals for bins:

my $binSize = 20; my $bin = 0; my $total = 0; while ((my $line = <DATA> // '') || defined $bin){ chomp $line; my ($chr, $pos, $coverage) = split /\t/, $line; my $thisBin; $thisBin = int(($pos - 1) / $binSize) if defined $pos; if (! defined $thisBin || $bin != $thisBin) { printf "%4d %d\n", 20 * (1 + $bin), $total; last if ! defined $thisBin; $bin = $thisBin; $total = 0; } $total += $coverage; }
True laziness is hard work

In reply to Re: How to calculate sum of a column by window size based on another column by GrandFather
in thread How to calculate sum of a column by window size based on another column by rnaeye

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.