Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Calculating percentage of change between columns

by choroba (Cardinal)
on May 29, 2013 at 23:39 UTC ( [id://1035932]=note: print w/replies, xml ) Need Help??


in reply to Calculating percentage of change between columns

Note that your sample output is wrong. If going from 4 to 4 changes 0%, than going from 6 to 8 should change 33%, not 133%. Also, you cannot express the change going anywhere from 0.

You might find the following code useful. I have modified some values to show some other interesting results.

#!/usr/bin/perl use warnings; use strict; my %hash = ( file1 => { foo => 4, bar => 6, baz => 4, quux => 8, quuux => 6, quuuux => 0, }, file2 => { foo => 4, bar => 8, baz => 4, quux => 8, quuux => 5, quuuux => 0, }, file3 => { foo => 8, bar => 0, baz => 5, quux => 8, quuux => 5, quuuux => 3, }, ); my %columns = map { $_ => 1 } map keys %{ $hash{$_} }, keys %hash; my @files = qw/file1 file2 file3/; for my $column (keys %columns) { print $column, "\t", $hash{$files[0]}{$column}; for my $i (1 .. $#files) { my ($this, $previous) = map $hash{ $files[$_] }{$column}, $i, +$i - 1; print "\t", $this; my $change = '-'; if ($previous) { $change = sprintf "%d%%", 100 * ($this - $previous) / $pre +vious; } print "\t$change"; } print "\n"; }

Output:

bar 6 8 33% 0 -100% baz 4 4 0% 5 25% quuux 6 5 -16% 5 0% quux 8 8 0% 8 0% foo 4 4 0% 8 100% quuuux 0 0 - 3 -
لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Replies are listed 'Best First'.
Re^2: Calculating percentage of change between columns
by naChoZ (Curate) on May 30, 2013 at 17:56 UTC

    Perfect, thanks for that. The iterating of the array index and then using it in the map like you did with $this and $previous instead of the foreach style I was using was just what I needed.

    --
    Andy

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (5)
As of 2024-04-25 08:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found