Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Perl Sum & Count column based data

by ig (Vicar)
on Nov 15, 2013 at 03:54 UTC ( #1062696=note: print w/replies, xml ) Need Help??


in reply to Perl Sum & Count column based data

You say you are having difficulty, but you don't say what the difficulty is very clearly, making it difficult to help.

Perhaps the following will give you some ideas. Otherwise, you might be a bit more specific about what the difficulty is.

#!C:/strawberry/perl/bin/perl.exe # # See http://rick.measham.id.au/pdf-api2/ # use strict; use warnings; use Data::Dumper::Concise; my @records; while(my $record = <DATA>) { push(@records, [ split(/\s+/, $record) ]); } report({ group_by => 0, sum_columns => [ 2, 3 ], records => \@records, }); report({ group_by => 1, sum_columns => [ 2, 3 ], records => \@records, }); report({ group_by => 2, sum_columns => [ 3 ], records => \@records, }); exit(0); sub report { my ($args) = @_; # sum columns by group my %groups; foreach my $record (@{$args->{records}}) { my $group = $groups{$record->[$args->{group_by}]} //= {}; $group->{count}++; foreach my $sum_column (@{$args->{sum_columns}}) { $group->{sum}->{$sum_column} += $record->[$sum_column]; } } # produce output print "example output: group by column $args->{group_by}, sum colu +mns " . join(', ', @{$args->{sum_columns}}) . "\n"; foreach my $group (sort keys %groups) { print join(' ', $group, map { ( $groups{$group}->{count}, $groups{$group}->{sum}->{$_} ) } @{$args->{sum_columns}} ) . "\n";; } print "\n"; } __DATA__ U1 ID1 100 280 U1 ID1 137 250 U2 ID2 150 375 U1 ID2 100 100 U3 ID1 100 600 U9 ID3 137 200

Which produces:

example output: group by column 0, sum columns 2, 3 U1 3 337 3 630 U2 1 150 1 375 U3 1 100 1 600 U9 1 137 1 200 example output: group by column 1, sum columns 2, 3 ID1 3 337 3 1130 ID2 2 250 2 475 ID3 1 137 1 200 example output: group by column 2, sum columns 3 100 3 980 137 2 450 150 1 375

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1062696]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2020-09-27 01:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If at first I donít succeed, I Ö










    Results (142 votes). Check out past polls.

    Notices?