swati sinha
swati sinha

Reputation: 7

Grouping tabular data by multiple columns

I have the data in this format

b1  1995    1
b1  2007    0.1
b2  1974    0.1
b2  1974    0.6
b2  1975    0.3

And, I want to sum values in column 3 based on similar values in both columns 1 and 2.

I have written a code where it sums up the value but I do not know how to print the groups values.

use strict;
use warnings;
use Data::Dumper;
my $file=shift;
open (DATA, $file);
my %score_by_year;

while ( my $line = <DATA> )
{
        my ($protein, $year, $score) = split /\s+/, $line;
        $score_by_year{$year} +=$score;
        print "$protein\t$year\t$score_by_year{$year}\n";
}
close DATA;

so my code gives output as:

b1  1995    1
b1  2007    0.1
b2  1974    0.1
b2  1974    0.7
b2  1975    0.3

whereas, the expected output is this:

b1  1995    1
b1  2007    0.1
b2  1974    0.7
b2  1975    0.3

Upvotes: 0

Views: 38

Answers (1)

Skeeve
Skeeve

Reputation: 8212

To keep the sequence, store it:

use strict;
use warnings;

my @sequence;
my %scores_by_year;

while (<DATA>) {
   my ($protein, $year, $score) = split;
   if (not exists $scores_by_year{$protein}{$year}) {
     push @sequence, [$protein, $year];
   }
   $scores_by_year{$protein}{$year} += $score;
}

for my $protein_year (@sequence) {
  my($protein, $year)= @$protein_year;
  print join("\t", $protein, $year, $scores_by_year{$protein}{$year}), "\n";
}
__DATA__
b1  1995    1
b1  2007    0.1
b2  1974    0.1
b2  1974    0.7
b2  1975    0.3

Upvotes: 1

Related Questions